When dealing with a dynamic list of elements, it can be challenging to achieve a centered layout while also aligning the last row of elements to the left. While text-align: center aligns elements horizontally within their container, it doesn't consider the width of the container.
CSS Grid provides a solution to this problem:
div { display: grid; justify-content: center; }
However, to ensure that the last row of elements aligns to the left, we need to specify the number of columns in the grid using grid-template-columns:
ul { grid-template-columns: repeat(auto-fit, 40px); }
Example:
<div> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div>
With this solution, the boxes remain centered horizontally while the last row aligns to the left, regardless of the number of elements in the list.
The above is the detailed content of How to Center Boxes with a Left-Aligned Last Row Using CSS Grid?. For more information, please follow other related articles on the PHP Chinese website!