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
To align the item horizontally within the grid, we use the justify-content property and set it to center . With justify-content we can align the columns start , end , stretch or center .
Using transform. The translate() CSS function moves an element along the x- and y-axes. Using it together with the transform property allows you to change the position of a grid item.
To center the last one, you can double the number of columns to 4 and set each item to span 2 . If the last item is odd, start on the second column so it spans columns 2 and 3. With a bit of math and SCSS, this can be generalized to work with any number of columns.
Instead set column width:100px inside the grid, because grid is the container also use justify-content:end; to align the content to the right side.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With