Home >Web Front-end >CSS Tutorial >How to Center the Last Row of Items in a CSS Grid Layout?

How to Center the Last Row of Items in a CSS Grid Layout?

Linda Hamilton
Linda HamiltonOriginal
2025-01-02 16:04:42175browse

How to Center the Last Row of Items in a CSS Grid Layout?

How to Achieve Center Alignment on the Last Row of a CSS Grid

When using CSS Grid to layout elements, it becomes challenging to achieve center alignment on the last row due to the nature of grid tracks. However, flexbox provides a more suitable solution for such alignment requirements.

To align the last row of items horizontally in the center, apply flexbox properties to the container element:

#container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

The flex-wrap: wrap property allows items to flow into multiple rows if necessary, while justify-content: center packs all items in the horizontal direction relative to the entire row.

Next, set the flex behavior for individual items:

.item {
  flex: 0 0 calc(16.66% - 20px);
  background: teal;
  color: white;
  padding: 20px;
  margin: 10px;
}

Here, flex: 0 0 calc(16.66% - 20px) specifies the item's dimensions and ensures that all items are equally sized. box-sizing: border-box should be included for precise calculations.

As a result, items will be distributed evenly across the rows, and the last row will be centered due to the justify-content: center property. This approach eliminates the limitations of CSS Grid and provides a flexible solution for centering last row items for an arbitrary number of elements.

The above is the detailed content of How to Center the Last Row of Items in a CSS Grid Layout?. 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