Margin after float

Saturday 29th May

Margins often behave in frustrating ways when combined with floated elements. Here’s a quick solution to one such problem.

Take this following example, in which an element with a top margin, following two floated elements, ‘sticks’ right up against those elements:

A cleared element

Even though it’s clearing those floats (with clear: both), its margin doesn’t position it away from them. In fact, that margin is effectively ‘hidden’ behind the floats (to verify this, hover your pointer over the cleared element).

It’s tempting to get around this by introducing an extra element — either an empty clearing element just after the floats, or a wrapper around them. However, in the interests of keeping markup as clean as possible, it’s often appropriate to just add bottom margin to the floats:

A cleared element

Try hovering your pointer over the first floated element to view the margin. In some cases, you might want to add that margin to all such floated elements — if they might have variable heights, for example.


Tweet

Comments

Mon 4 Apr 2011 18:32

jiro brasen

jiro brasen said:

Impressive…Thank you for sharing!

Tue 28 Jun 2011 23:48

Vyb

Vyb said:

thanks!

Tue 9 Aug 2011 00:16

misho

misho said:

Thanks for your help!

Thu 11 Aug 2011 12:09

Jay Levitt

Jay Levitt said:

But, but… WHY does it happen?

Sat 12 May 2012 15:22

Josh G.

Josh G. said:

Wow, elegant solution to a problem I just couldn’t understand.

Thank you so much!

Leave a comment