Home >Web Front-end >CSS Tutorial >How Can I Align the Last Row of a Flexbox Grid Evenly with `justify-content: space-between`?

How Can I Align the Last Row of a Flexbox Grid Evenly with `justify-content: space-between`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-21 22:20:21120browse

How Can I Align the Last Row of a Flexbox Grid Evenly with `justify-content: space-between`?

Flex-Box: Aligning the Last Row to the Grid

In a flex-box layout, aligning items in the last row with the others can present a challenge. With justify-content: space-between;, adjusting the grid's size can throw off the alignment.

To resolve this issue, a simple and elegant solution emerged:

Using ::after

Add a ::after pseudo-element that autofills the remaining space:

.grid {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.grid::after {
  content: "";
  flex: auto;
}

How it Works:

The ::after pseudo-element creates a virtual element that fills the empty space in the grid. By giving it flex: auto;, it automatically adjusts to fit. Thus, the last row items align seamlessly regardless of grid size, and without modifying the HTML structure.

For a live demonstration, refer to the provided CodePen example here: http://codepen.io/DanAndreasson/pen/ZQXLXj

The above is the detailed content of How Can I Align the Last Row of a Flexbox Grid Evenly with `justify-content: space-between`?. 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