Home >Web Front-end >CSS Tutorial >How Can CSS Grid Center Boxes While Left-Aligning the Last Row?
Centering and Left-Aligning Boxes with CSS Grid
Many users have encountered challenges in aligning boxes centrally while also aligning their last row to the left. By default, ul elements often have a fixed width that does not adapt to their content, making it difficult to achieve both centering and left alignment automatically.
CSS Grid Solution
To resolve this issue, CSS grid can be employed. By implementing the following CSS properties, you can center boxes while left-aligning their last row:
div { padding: 20px; width: 200px; border: 1px solid; overflow: hidden; resize: horizontal; } ul { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fit, 40px); /* Width of elements */ grid-auto-rows: 40px; /* Height of elements */ grid-gap: 4px; justify-content: center; /* Centers boxes */ } ul li { background-color: wheat; }
HTML Code
<div> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div>
Explanation
The grid-template-columns and grid-auto-rows properties define the number of columns and rows in the grid. The grid-gap property sets the spacing between the elements. The key to both centering and left-aligning is the justify-content property. When set to "center", it positions the grid items in the horizontal center of their available space within the parent container. This ensures the boxes are centered, with the last row being aligned to the left as it comes at the end of the grid.
The above is the detailed content of How Can CSS Grid Center Boxes While Left-Aligning the Last Row?. For more information, please follow other related articles on the PHP Chinese website!