Explain Codes LogoExplain Codes Logo

How can I stop float left?

css
best-practices
responsive-design
performance
Alex KataevbyAlex Kataev·Dec 3, 2024
TLDR

To prevent floating elements, you can use clear: both; for the element appearing after your float. This stops any further elements from wrapping around the float.

A simple solution would be:

.stop-float { clear: both; /* "I ain't floating anywhere" */ }

And for HTML:

<div class="float-left">Floating away...</div> <div class="stop-float">Not on my watch!</div>

Sometimes containers might cause an issue. To contain your floats, you could use a clearfix:

.clearfix::after { content: ""; display: table; /* Cleaning up after float's mess */ clear: both; }

Here's how you can add clearfix to your container thus ensuring all your floats are tidied up:

<div class="clearfix">I got this</div>

Making your float behave

Take away the float privilege with float: none

If you want your element to take a break from floating, simply set its float property to none.

.adm { float: none; /* "I am on a floating strike" */ }

The above ".adm" class now ensures that the element does not float and gets back with the crowd.

Get rid of the float label

In case you want your "adm" class to stop floating without resorting to inline styles, you can just tweak or remove the class causing it to float.

.adm { clear: both; }

This tweak ensures that "adm" class clears the float and nicely settles on a new line.

Control your float's journey

By using an inline style with clear: both;, you force the element to buckle up and start on a new line, effectively telling the float to stop.

<div class="float-left">Just floating around</div> <div style="clear:both;"></div> <!-- "You shall not pass!" --> <div class="adm">I follow rules</div>

TIP: Just add a non-floating divider once you are done with your floated elements. This ensures that the content that follows lines up on a new row.

Float logistics

Pitfall of inline styles

Even though inline styles can provide quick results, they tend to create CSS-in-HTML chaos and slows down future modifications. It's always a good idea to define clearing methods in your stylesheet.

Playing with older browsers

The clear property is a modern feature. If you need to support the retro browsers, you might consider using height adjustments or overflow properties as your sidekick.

What did floats ever do to us?

With the advent of Flexbox and Grid, you can take a vacation from using floats. These modern layout marvels, provide a no-nonsense way to layout your pages without the quirks that come with floats.

The risk of floating too much

Floats are like that extra slice of cake. Too many of them and you'll end up with layout bugs. Watch out for mysterious wrapping or spacing—these are signs of bad float digestion.