Home >Web Front-end >CSS Tutorial >How to Justify Flex Item Widths on the Last Row Without Stretching?

How to Justify Flex Item Widths on the Last Row Without Stretching?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 11:06:07452browse

How to Justify Flex Item Widths on the Last Row Without Stretching?

Justifying Flex Item Widths on the Last Row

The challenge arises when trying to distribute elements evenly across the container, except for the last row. Simply aligning the elements using text-align: justify doesn't suffice, as there are no spaces between the elements. Flexbox provides a solution, but the default behavior stretches the last line's elements across the full width.

To achieve justify-align-like behavior, where elements use the natural width on the last line, use the following approach:

  1. Add Phantom Items:
    Create several "phantom" items that occupy the last slots of the container. These items can be hidden with visibility: hidden.

For example, with user #82 as the last entry, add fake users 83, 84, and 85 with visibility: hidden.

  1. Use a Sole Phantom Item:
    Alternatively, use a single phantom item at the end with visibility: hidden and flex-grow: 10. Target it using the :last-child or :last-of-type pseudo-class.

This method allows the last line's elements to maintain their natural width while distributing the remaining space evenly across the phantom items.

The above is the detailed content of How to Justify Flex Item Widths on the Last Row Without Stretching?. 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