Home > Web Front-end > CSS Tutorial > How to Center Boxes Horizontally and Align the Last Row to the Left with CSS Grid?

How to Center Boxes Horizontally and Align the Last Row to the Left with CSS Grid?

Barbara Streisand
Release: 2024-12-22 20:39:06
Original
382 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template