Home > Web Front-end > CSS Tutorial > How to Left-Align the Last Line in a Multi-Line Flexbox Layout?

How to Left-Align the Last Line in a Multi-Line Flexbox Layout?

Mary-Kate Olsen
Release: 2024-11-03 19:02:29
Original
529 people have browsed it

How to Left-Align the Last Line in a Multi-Line Flexbox Layout?

Left-Aligning Last Line in Multi-Line Flexbox

In flexbox layouts, aligning the last line to the left side can present challenges when the last line does not contain the same number of elements as other lines. This irregularity disrupts the desired grid effect.

To resolve this issue, we can employ a technique using "filling-empty-space-childs" divs. These divs have zero height, allowing them to collapse into a new line without affecting the layout.

Consider the following HTML code:

<code class="html"><div class="container">

    <div class="item"></div>
    <div class="item"></div>
    ...
    <div class="item"></div>

    <div class="filling-empty-space-childs"></div>
    <div class="filling-empty-space-childs"></div>
    <div class="filling-empty-space-childs"></div>

</div></code>
Copy after login

And the corresponding CSS:

<code class="css">.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
}

.container .item { width: 130px; height: 180px; background: red; margin: 0 1% 24px; }

.filling-empty-space-childs {
    width: 130px; /*match the width of the items*/
    height: 0;
}</code>
Copy after login

In this solution, the "filling-empty-space-childs" divs occupy the remaining space in the last line. If the last line has four elements, these divs will collapse into a new line, invisible and occupying no space. However, if there are fewer than four elements, the extra "filling-empty-space-childs" divs will align the last elements to the left side, maintaining the grid effect.

The above is the detailed content of How to Left-Align the Last Line in a Multi-Line Flexbox Layout?. 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