Flex box design to maintain div width when moved to next line using flex-wrap

Viewed 31

I have this demo code where the width of 5 , 6 and 7 are not as it is with above divs.

An easy way is to add empty divs which are hidden. But, is there a better way ?

.parent-wrapper {
    height:100%;
    width: 400px;
    border: 1px solid black;
}
.parent {
    display: flex;
    flex-wrap:wrap;
}
.child {
    background:blue;
    flex: 1 0 21%;
    height:100px;
    margin: 5px;
}
<body>
    <div class="parent-wrapper">
        <div class="parent">
            <div class="child">1</div>
            <div class="child">2</div>
            <div class="child">3</div>
            <div class="child">4</div>
            <div class="child">5</div>
            <div class="child">6</div>
            <div class="child">7</div>
        </div>
    </div>
</body>

In the end, I want to render it using some dynamic value so I think a CSS way would be better than adding empty divs

2 Answers

How about not asking it to grow, demo here

.child {
    background:blue;
    flex: 0 0 21%; //<-- note 0 here
    height:100px;
    margin: 5px;
}

If you can use CSS grid, it is easy to be done as below example:

.parent-wrapper {
  height:100%;
  width: 400px; 
}
.parent {
  display: grid;
  grid-template-columns: repeat(4, 100px);
  gap: 5px;
}
.child {
  background:blue;
  height:100px;
}
  <div class="parent-wrapper">
    <div class="parent">
      <div class="child">1</div>
      <div class="child">2</div>
      <div class="child">3</div>
      <div class="child">4</div>
      <div class="child">5</div>
      <div class="child">6</div>
      <div class="child">7</div>
    </div>
  </div>

Related