Edit: looks like this has been asked before, and the answer was that as of 2024 there is no general solution that is agnostic to the number of items or columns in the grid.
I have this very simple grid of buttons, like a telephone dial pad. The last row does not have enough items to fill it, and I want that row’s items lined up to the right so that the gap is on the left. justify-content
, align-content
, justify-items
, and align-items
do not do this. Please do not tell me to set one of those properties to end
unless you have a codepen showing that it works, because it does not accomplish this.
Is it even possible to do this with css grid? I’m aware I could put in an invisible "bumper" div to shunt that row over, but I’m just wondering if it’s possible to control this alignment with CSS alone.
<div className="inputPanel">
<div className="button">1</div>
<div className="button">2</div>
<div className="button">3</div>
<div className="button">4</div>
<div className="button">5</div>
<div className="button">6</div>
<div className="button">7</div>
<div className="button">8</div>
<div className="button">9</div>
<div className="button">0</div>
<div className="button">←</div>
</div>
with css:
.inputPanel {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 5px;
margin-top: 30px;
.button {
padding: 20px;
text-align: center;
background-color: #d3d6da;
border: 1px solid #ccc;
border-radius: 2px;
font-size: 24px;
cursor: pointer;
}
}
3
Answers
As you know that it’s the second from last element that needs to move to column 2 you can use nth-last-child(2) to position it within the grid.
The last element will then follow to the next column.
You can try giving
justify-self: end;
to the last twodivs
.But: You guessed it right: Use an invisible spacer div. This is the common approach straight forward, which is everywhere seen in any code: