Home > Web Front-end > CSS Tutorial > How Can I Fix Layouts Broken by Floated Elements with Different Heights?

How Can I Fix Layouts Broken by Floated Elements with Different Heights?

Patricia Arquette
Release: 2024-12-19 16:35:10
Original
301 people have browsed it

How Can I Fix Layouts Broken by Floated Elements with Different Heights?

Floated Elements with Varying Heights Breaking Layout

When working with floated elements of variable heights, maintaining a clean layout can be a challenge. One such scenario is when some elements are taller than others, causing subsequent siblings to shift out of alignment.

To address this issue, CSS offers a clever solution:

CSS Rule for Aligning Floated Elements

figure:nth-of-type(3n+1) {
    clear: left;
}
Copy after login
Copy after login

This rule instructs the browser to clear the floated elements every three elements, starting with the first. In other words:

  • After the first, fourth, and seventh elements, the float is cleared, allowing subsequent siblings to start a new line.
  • This ensures that the second row of elements aligns directly below the first three, regardless of their heights.

Example

Consider the provided HTML and CSS:

<figure> // Figure 1
    ...
</figure>
<figure> // Figure 2
    ...
</figure>
<figure> // Figure 3
    ...
</figure>
<figure> // Figure 4
    ...
</figure>
<figure> // Figure 5
    ...
</figure>
<figure> // Figure 6
    ...
</figure>
Copy after login
figure {
    width: 30%;
    float: left;
    ...
}
Copy after login

By adding the clear: left rule:

figure:nth-of-type(3n+1) {
    clear: left;
}
Copy after login
Copy after login

The layout is corrected, and the second row of figures aligns below the first three:

[Image: Corrected layout with second row of figures aligned below the first three]

Conclusion

Utilizing the clear: left rule provides an elegant and efficient way to ensure that floated elements of varying heights align properly, maintaining a clean and organized layout.

The above is the detailed content of How Can I Fix Layouts Broken by Floated Elements with Different Heights?. 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