Home >Web Front-end >CSS Tutorial >How Can I Make the Last Row in a CSS Grid Span the Entire Row?
Filling the Last Row in CSS Grid
In CSS Grid, a common challenge is to ensure that items in the last row occupy the entire row. Without knowing the exact number of items, solutions may seem elusive.
Using nth-child and nth-last-of-type
This can be achieved using a combination of CSS rules: nth-child and nth-last-of-type. These rules target elements based on their position within a specific parent element. With these rules, it's possible to adjust the alignment and sizing of items in the last row.
Sample Code:
Consider the following CSS code:
.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; }
Explanation:
The above is the detailed content of How Can I Make the Last Row in a CSS Grid Span the Entire Row?. For more information, please follow other related articles on the PHP Chinese website!