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; }
This rule instructs the browser to clear the floated elements every three elements, starting with the first. In other words:
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>
figure { width: 30%; float: left; ... }
By adding the clear: left rule:
figure:nth-of-type(3n+1) { clear: left; }
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!