1

I'm trying to center align some columns in a grid, but only when there aren't enough items in the container to cause it to wrap onto more than one row. When the wrapping kicks in the items should be aligned to the left. The number of items in the grid is dynamic and the widths are specified as a percentage.

I'm currently using flexbox but have also looked at css-grid. I know I could achieve this easily by adding another class to the container if there are less items than the number of columns in a row, but I'm looking for a CSS-only solution if possible. I've been looking for a way to target any elements that get wrapped onto another row and override justify-content, but I think I might be approaching this in the wrong way. It seems like it should be so easy!

.grid {
  display: flex;  
  flex-wrap: wrap;
  justify-content: center;
  background: pink;
}
.column {
  width: 25%;
  height: 100px;
  background: green;
  border: 1px solid black;
  box-sizing: border-box;
}
.justify-left {
  justify-content: left;
}
<h2>How it looks with less than 4 items</h2>  
<div class="grid">
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
</div>

<h2>How it looks with more than 4 items</h2>  
<div class="grid">
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
</div>
  
<h2>How it should look with more than 4 items</h2>  
<div class="grid justify-left">
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
  <div class="column"></div>
</div>
  • so your question is, how can we make css inconsistent? :D #doh – OZZIE Jan 07 '19 at 18:58
  • You could make the first row it's own flex row (with justify-content: center), but I'm guessing that's not the solution you're looking for. – Rice_Crisp Jan 07 '19 at 19:00

0 Answers0