Home > Web Front-end > CSS Tutorial > How to Center Boxes with a Left-Aligned Last Row Using CSS Grid?

How to Center Boxes with a Left-Aligned Last Row Using CSS Grid?

Mary-Kate Olsen
Release: 2024-12-17 00:36:26
Original
293 people have browsed it

How to Center Boxes with a Left-Aligned Last Row Using CSS Grid?

Centered Boxes with Left-Aligned Last Row

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.

Resolving the Issue

CSS Grid provides a solution to this problem:

div {
  display: grid;
  justify-content: center;
}
Copy after login
  • display: grid converts the container into a grid layout.
  • justify-content: center horizontally centers the contents of the grid.

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);
}
Copy after login
  • repeat(auto-fit, 40px) creates as many columns as necessary to fit the content, each with a width of 40px.

Example:

<div>
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</div>
Copy after login

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!

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