Home > Net >  Nested row flexbox with wrapping on multiple levels
Nested row flexbox with wrapping on multiple levels

Time:08-30

I am making responsive design where elements wrap to next line in certain way when there is not enough space, however I cannot make it working.

Requirements:

  1. There are 3 elements (actually more, but this is minimal example), all with automatic size depending on their content: one aligned on the left, two - on the right.
  2. They are placed inside container which always spans at least 100% width of parent.
  3. If there is not enough space for elements to be all on one line, then right element should begin to wrap to next line, while still all being to the right of left element.
  4. If there is still not enough space, only then right elements go under left one.
  5. If there is still not enough space, then container expands in size.

Here are examples how it should work (red lines represent viewport borders):

requirements examples

Here is code I come up with so far, but it starts wrapping immediately on outer level, not on innermost as I need:

html, body {
  width: 100%;
  height: 100%;
}
* {
  margin: 0;
  padding: 0;
  flex: 0 0 auto;
}
#container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  overflow: hidden;
  width: 100%;
  min-width: min-content;
  background-color: rgb(224, 191, 146); /* for visibility */
}
#child-left {
  background-color: rgb(92, 189, 40); /* for visibility */
  /* imitate content for demo, in actual code size is not set */
  width: 50vw;
  height: 50px;
}
#child-right {
  display: flex;
  flex-flow: row wrap;
  background-color: rgb(111, 72, 20); /* for visibility */
}
#grandchild-right-1 {
  background-color: rgb(40, 102, 189); /* for visibility */
  /* imitate content for demo, in actual code size is not set */
  width: 200px;
  height: 20px;
}
#grandchild-right-2 {
  background-color: rgb(189, 40, 112); /* for visibility */
  /* imitate content for demo, in actual code size is not set */
  width: 200px;
  height: 20px;
}
<div id="container">
  <div id="child-left">1</div>
  <div id="child-right">
    <div id="grandchild-right-1">2</div>
    <div id="grandchild-right-2">3</div>
  </div>
</div>

CodePudding user response:

You can achieve this by using flex: 1.

Remember that flex is a shorthand property for flex: 1 1 0 or flex-grow: 1, flex-shrink: 1 and flex-basis: 0. As a result, this makes the elements take any empty space in the container, hopping to the next line if theres no space left.

https://css-tricks.com/understanding-flex-grow-flex-shrink-and-flex-basis/

  • Related