Challenge:
How can we ensure that all items in the last row of a CSS grid consume the remaining space in the row, regardless of their number?
Solution:
Leveraging the power of CSS grid, we can achieve this spatial control through a clever combination of nth-child and nth-last-of-type rules. The key lies in knowing the number of columns in the grid beforehand.
Implementation:
Example 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; }
HTML Example:
<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>
By harnessing the power of these CSS properties, we can effectively control the spacing of items in the last row of a CSS grid, ensuring an aesthetically pleasing and flexible layout.
The above is the detailed content of How Can I Make CSS Grid's Last Row Items Fill Remaining Space?. For more information, please follow other related articles on the PHP Chinese website!