How do I get a new line, after using float:left?
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:
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.
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:
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:
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"
:
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.
Was this article helpful?