Tuesday, February 2, 2021

Flexbox Row/Column

I've been working more towards using Flexbox and away from Bootstrap's column layout as much as possible. I love the column layout, but it still feels janky to me sometimes and Flexbox seems a lot smoother. I was recently updating a page that uses columns to display 3 items on a row and each item  (with margins and padding) takes up 33% of the row. When there are 4 items, there are 2 rows with 3 items on the first row and 1 item on the second row, but the single item on the second row still only takes up 33% of the second row.

I was able to accomplish this using the following markup and CSS.

<div class="d-flex flex-wrap">
  <div class="item">
    ...single item contents...
  </div>
  <div class="item">
    ...single item contents...
  </div>
  <div class="item">
    ...single item contents...
  </div>
  <div class="item">
    ...single item contents...
  </div>
</div>
.item {
  flex: 0 0 33%;
}

At one point I had flex: 1 0 33% and that was really close, except the one item on the second line took up the entire line. This works beautifully and I'm happy because I get to use flexbox.

No comments:

Post a Comment