CSS Grid how to push items to the bottom and then to the left

Viewed 1923

I have a grid with 5 buttons with only 2 buttons per row. If there's an odd number of buttons I want the first row to only have one button.

My css:

.container {
 display: grid;
 grid-template-columns: 1fr 1fr;
 grid-template-rows: 1fr 1fr;
}
<div class="container">
    <button>A</button>
    <button>B</button>
    <button>C</button>
    <button>D</button>
    <button>E</button>
</div>

Layout:

A B
C D
E

Desired Layout:

A
B C
D E
2 Answers

In other words, you want your second button, when it is in an even position counting from the last, to be in the first column:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 1fr;
  margin: 10px;
}

.container button:nth-child(2):nth-last-child(even) {
  background-color: yellow;
  grid-column: 1;
}
<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
  <button>D</button>
  <button>E</button>
</div>

<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
  <button>D</button>
</div>

<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
</div>

<div class="container">
  <button>A</button>
  <button>B</button>
</div>

A flexbox idea:

.container {
  display: flex;
  flex-wrap:wrap;
  margin: 10px;
}
.container button {
  width:50%;
}

.container button:first-child:nth-last-child(odd) {
  margin-right:1px; /* a tiny margin to push the next element */
}
<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
  <button>D</button>
  <button>E</button>
</div>
<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
  <button>D</button>
</div>

<div class="container">
  <button>A</button>
  <button>B</button>
  <button>C</button>
</div>

<div class="container">
  <button>A</button>
  <button>B</button>
</div>

Related