-1

I defines a column div with width 25%, and the 5th element floats to right in the second row because 2nd element has a bigger height. I can solve the problem by defining a fixed height, so the 2nd row will starts from 1st column in the left. But I wonder if there is a better solution with CSS itself. My goal is to create a photo gallery to display all photos in a folder with filename as description so the height could be different, and I don't want to define another "row" div and specify files for each row. enter image description here

<style>
.column {
  float: left;
  width: 25%;
}
</style>

<div class="column" style="background-color:#aaa;">
  <h2>Column 1</h2>
  <p>Some text..</p>
</div>

<div class="column" style="background-color:#ccc;">
  <h2>Column 2</h2>
  <p>Some long text..........................................................................................</p>
</div>

<div class="column" style="background-color:#ddd;">
  <h2>Column 3</h2>
  <p>Some text..</p>
</div>

<div class="column" style="background-color:#eee;">
  <h2>Column 4</h2>
  <p>Some text..</p>
</div>

<div class="column" style="background-color:#eee;">
  <h2>Column 5</h2>
  <p>Some text..</p>
</div>

codepen

Peter Xie
  • 19
  • 1

1 Answers1

-1

Flexbox was made for this use case. We put everything in a flexbox container and enable flex-wrap so that items wrap around. The items in the flex container will size and position themselves accordingly. Since you've specified a 25% width, when there's more than 4 items the flex will wrap and put the next item on a next line.

<style>
.container {
  display: flex;
  flex-wrap: wrap;
}
.column {
  width: 25%
}
</style>

<div class="container">
<div class="column" style="background-color:#aaa;">
    <h2>Column 1</h2>
    <p>Some text..</p>
  </div>
  
  <div class="column" style="background-color:#ccc;">
    <h2>Column 2</h2>
    <p>Some long text..........................................................................................</p>
  </div>
  
  <div class="column" style="background-color:#ddd;">
    <h2>Column 3</h2>
    <p>Some text..</p>
  </div>
  
  <div class="column" style="background-color:#eee;">
    <h2>Column 4</h2>
    <p>Some text..</p>
  </div>
  
  <div class="column" style="background-color:#eee;">
    <h2>Column 5</h2>
    <p>Some text..</p>
  </div>
</div>
xy2
  • 6,040
  • 3
  • 14
  • 34