Home > Web Front-end > CSS Tutorial > How to Perfectly Align Flex Items on the Last Row with Unpredictable Widths?

How to Perfectly Align Flex Items on the Last Row with Unpredictable Widths?

Mary-Kate Olsen
Release: 2024-12-06 15:00:15
Original
653 people have browsed it

How to Perfectly Align Flex Items on the Last Row with Unpredictable Widths?

How to Perfectly Size and Align Flex Items on the Last Row

When working with a list of flex items, you may encounter inconsistencies in the right edge alignment, especially when the item widths are unpredictable or dynamic. While fixed widths or display:table techniques may not yield satisfactory results, consider the following approach using flexbox for precise size and alignment control:

Solution using Flexbox:

  1. Set the parent container to display: flex; and flex-wrap: wrap; to allow for multiple rows.
  2. Apply flex: 1 0 auto; to the flex items to make them flexible and shrink as needed.

However, if this results in the last row stretching too wide, you can implement the following workaround:

Phantom Item Trick:

To achieve justify-align-like behavior, consider creating "phantom" flex items that always occupy the last slots. This can be done by adding the following code to the parent container:

.parent-container:after {
    content: '';
    flex: 10 0 auto;
}
Copy after login

This phantom item will automatically adjust its width to fill the remaining space on the last row, ensuring that the true flex items maintain their natural widths.

Implementation Example:

In the given example, you can implement the solution as follows:

.userlist {
    display: flex;
    flex-wrap: wrap;
}

.userlist:after {
    content: '';
    flex: 10 0 auto;
}
Copy after login

This will create a single phantom item that will always occupy the last slot in the .userlist container, resulting in the desired spacing and alignment.

The above is the detailed content of How to Perfectly Align Flex Items on the Last Row with Unpredictable Widths?. 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