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
Mary-Kate OlsenOriginal
2024-12-17 00:36:26302browse

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;
}
  • 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);
}
  • 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>

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!

Statement:
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