Home >Web Front-end >CSS Tutorial >How to Center Boxes Horizontally and Align the Last Row to the Left with CSS Grid?
Align Last Row of Centered Boxes to Left Using CSS Grid
Q: How can I center boxes horizontally but align the last row to the left?
A: Using the CSS grid property, it's possible to achieve this alignment scenario without manual adjustments or scripting.
To achieve this, modify the following CSS properties:
div { /* Add resize property for dynamic width adjustment */ resize: horizontal; /* Add justify-content property to center the boxes horizontally */ justify-content: center; } ul { display: grid; /* Define the number of columns based on the number of boxes */ grid-template-columns: repeat(auto-fit, 40px); /* Define the height of the boxes */ grid-auto-rows: 40px; /* Add grid-gap property for spacing between boxes */ grid-gap: 4px; }
By specifying justify-content: center, the boxes will be centered horizontally within the container. The display: grid property will align the last row of boxes to the left, as specified in the grid system.
The resize: horizontal property allows for dynamic adjustment of the container's width. As the width changes, the boxes will automatically rearrange to fit within the available space while maintaining their centered alignment.
The above is the detailed content of How to Center Boxes Horizontally and Align the Last Row to the Left with CSS Grid?. For more information, please follow other related articles on the PHP Chinese website!