manski's blog

CSS clearfix with LESS

The idea of CSS is to separate design from structure (which is represented by HTML). So much for the theory. In pratice, however, this doesn’t always work – or at least the solution isn’t very obvious.

One of the most prominent examples is the so called clearfix. It solves the floating elements problem (described below) but usually requires you to change your HTML code.

Fortunately, with LESS (a better CSS) this is no longer necessary.

The Problem

If you already know what problem the clearfix fixes, you can skip this section.

Assume the following HTML code (inline CSS just for demonstration purposes):

<div class="red-box">
  <div class="yellow-box" style="float: left">Float 1</div>
  <div class="yellow-box" style="float: left">Float 2</div>
  <div>Some text here</div>
</div>

(Full Code)

This will render as:

Float 1
Float 2
Some text here

 

As you can see, although the red box encloses the yellow boxes in HTML, it doesn’t enclose them when being displayed.

What we (usually) want is this:

Float 1
Float 2
Some text here
 

This problem is fixed by the so called clearfix. Back in the day, you had to add a special <div> element inside the red box to apply the fix:

<div class="red-box">
  <div class="yellow-box" style="float: left">Float 1</div>
  <div class="yellow-box" style="float: left">Float 2</div>
  <div>Some text here</div>
  <div style="clear:both"></div>
</div>

With the advent of the CSS pseudo classes :after and :before one could create the clear fix in CSS but still needed to apply a certain CSS class to the red-box <div>:

<div class="red-box clearfix">
  <div class="yellow-box" style="float: left">Float 1</div>
  <div class="yellow-box" style="float: left">Float 2</div>
  <div>Some text here</div>
</div>

Clearfix with LESS

Fortunately with LESS you can apply the clearfix without changing your HTML code.

You need this LESS code:

.group {
  zoom: 1; // For IE 6/7 (trigger hasLayout)

  &:before, &:after {
    content: "";
    display: table;
  }

  &:after {
    clear:both;
  }
}

Now, all you need to do is to add the CSS class via mixin:

.red-box {
  background:red; 
  color:white; 
  padding: 5px;
  .group; // mixin
}

That’s it.

Note: The CSS class is called group (instead of clearfix) which is more semantic.

No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *