Explain Codes LogoExplain Codes Logo

How do I get a new line, after using float:left?

html
responsive-design
css
float-clearing
Nikita BarsukovbyNikita Barsukov·Nov 22, 2024
TLDR

To drop next content on a new line after a float:left; element, use clear: both; on the immediate following element. Here's a simple fix:

<div style="float: left;">Floating along...</div> <!-- Clear float --> <div style="clear: both;"></div> <div>I'm on a new level!</div>

This <div> styled with clear: both; ensures any subsequent content shifts below the floated item(s) onto a new line.

Advanced float clearing strategies

In more complex scenarios, like after every 6 images in a gallery, you need to clear floats strategically. Consider the following techniques:

CSS pseudo-element to the rescue

Here, we don't need additional HTML elements.

.gallery:after { content: ""; display: table; clear: both; }

This automatically clears the floats within the .gallery class.

Lists for cleaner HTML (and life)

When dealing with multiple elements, semantic HTML tags such as ul and li form a clear boundary between rows:

<ul class="photos"> <li><img src="beach.jpg" alt="Beach"></li> <!-- More beach pics --> </ul>
.photos { list-style: none; padding: 0; width: calc(100% - 10px); /* Because breathing space matters */ } .photos li { float: left; width: calc(16.66% - 10px); /* Because maths is cool */ margin-right: 10px; } .photos li:nth-child(6n+1) { clear: both; }

This CSS command means: "After every 6 images, let's have a new row."

Flexing with Flexbox

Though floats are traditional, CSS Flexbox is a refreshing solution that automatically aligns items to the next line, meaning goodbye to clearing floats:

.flex-container { display: flex; flex-wrap: wrap; } .flex-item { width: 16.66%; /* Let's bring calculators back */ }

Watch out! Common issues and solutions

Overlapping fever

If elements above float aren't cleared right, overlap issues arise. Throws off layout, doesn't it? Ensure every clear: both; is in place or deploy a .clearfix class like our buoy.

Legacy HTML/CSS nerves

Older websites may cramp your style. In such cases, use an old-school br tag with clear="all":

<br clear="all" /> <!-- We go vintage sometimes! -->

Resisting responsiveness

Floats don't always behave well with different screens. Equip your layout with media queries or pick something flexible like the modern Flexbox or CSS Grid.