How to auto justify divs in CSS

I have a little question about CSS : I would like to do some responsive stuff with divs.

To be more precise, I would like to have a big div containing little divs inside. Those divs may vary in number, but they should all have a fixed size (for example, let's say 250px). So I would like to know if there is a way to make a kind of flex solution, so that divs are always justified, and as soon as the screen is to small to show for example 6 little divs per line, it only shows 5 divs per line.

I am pretty sure, that is not very clear, so here are two draws :

This is the first situation, the div is large enought to have 4 subdivs per line

Then, this div can't display 4 subdivs per line : so it shows 3 subdivs

Upvotes: 1

Views: 708

Answers (1)

Kyle
Kyle

Reputation: 347

Flexbox is useful here. Here's a Codepen that does what you're looking for:

https://codepen.io/ksmessy/pen/rmRbdL

As you shrink the window, the items will wrap to the next line. I separated the 3 flex properties in .flexparent with a line break so you can see what is causing this behavior.

HTML:

<div class="flexparent">
  <div class="flexchild"></div>
  <div class="flexchild"></div>
  <div class="flexchild"></div>
  <div class="flexchild"></div>
  <div class="flexchild"></div>
</div>

CSS:

.flexparent {
  border: 3px solid black;
  width: 550px;
  max-width: 100%;
  padding: 10px;
  box-sizing: border-box;

  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.flexchild {
  border: 1px solid red;
  width: 100px;
  height: 100px;
  margin: 10px;
}

Upvotes: 3

Related Questions