Home >Web Front-end >CSS Tutorial >How to Equally Distribute Items in the Last Row of a CSS Grid?
CSS Grid: Distributing Last Row Items Equally
In our web design endeavors, there often arises the need to evenly distribute items within a grid layout, particularly in the final row. This task is easily accomplished with the combined power of nth-child and nth-last-of-type rules. However, a prerequisite for this method is knowing the number of columns in your grid.
Consider the following markup:
<div class="grid"> <div>text</div> <div>TEXT</div> <div>text</div> <div>text</div> <div>TEXT</div> <div>text</div> <div>text</div> <div>TEXT</div> </div>
And these accompanying CSS rules:
.grid { display: grid; grid-template-columns: auto auto auto; justify-items: start; grid-gap: 10px; } .grid div { border: 1px solid #ccc; width: 100%; } .grid > *:nth-child(3n-1) { justify-self: center; text-align: center; } .grid > *:nth-child(3n) { justify-self: end; text-align: right; } .grid > *:nth-child(3n-1):nth-last-of-type(1) { border-color: red; grid-column: span 2; } .grid > *:nth-child(3n-2):nth-last-of-type(1) { border-color: red; grid-column: span 3; }
In this example, a grid is defined with three columns, and we specify the distribution and styling of the items within the last row using nth-child and nth-last-of-type. The borders are added to demonstrate the visual effect.
The css rules applied to nth-child(3n-1):nth-last-of-type(1) or nth-child(3n-2):nth-last-of-type(1) ensures that the last items in the second and third columns will span two or three columns, respectively and aesthetically consume the remaining space in the row.
The above is the detailed content of How to Equally Distribute Items in the Last Row of a CSS Grid?. For more information, please follow other related articles on the PHP Chinese website!