Start mapping your new career - Get 3 Months Free!
CSS

Solving the CSS floating element issue with Clearfix

Post image

When creating HTML and CSS layouts using float, it's common to come across the clearing issue for container div's. This is where you structure your design to have a containing element, such as div#content, inside it you have two div's - div#left, div#right. Now because the two elements are floating, the container can't see where to extend to so displays very flat, giving the appearence the floating elements have popped out of the container.

Introducing the sollution - clearfix.

The Basic Sollution - Old School

The basic sollution to this old-school problem is to place content below the floating elements but inside the container... simple!

But what if you don't have content to place after the floating elements?

Commonly, people simply place a blank clearing div after the floating elements and that does the trick.

Note: I've included the basic CSS styles within inline HTML/CSS to simplify the code. You don't have to do this!

HTML (with inline CSS):

<div id="content" style="display:block;">
	<div id="left" style="display:block; float:left; width: 75%;">
		<h1>Left Title</h1>
		<p>Left content paragraph.</p>
	</div>
	<aside id="right" style="display:block; float:right; width:25%;">
		<h3>Sidebar</h3>
		<ul>
			<li>List-item 1</li>
			<li>List-item 2</li>
			<li>List-item 3</li>
		</ul>
	</aside>
	<div class="clear" style="clear:both; display:block;"></div>
</div>

The Modern Sollution - CSS

In CSS 2 the :before and :after selectors were introduced. This enabled developers to solve the outstanding clearfix issue in a simple way that didn't clutter the HTML with empty elements.

What this clearfix method does is place a "." after all the content, it then sets the height to 1px and hides the content so it's invisible.

A simple sollution for an annoying, age-old CSS problem.

\

CSS:

.clear {
	display: block;	
}
	
	.clear::after {
		clear: both;
		content: ".";
		display: block;
		height: 1px;
		visibility: hidden;
	}		

Revised HTML:

<div id="content" class="clear" style="display:block;">
	<div id="left" style="display:block; float:left; width: 75%;">
		<h1>Left Title</h1>
		<p>Left content paragraph.</p>
	</div>
	<aside id="right" style="display:block; float:right; width:25%;">
		<h3>Sidebar</h3>
		<ul>
			<li>List-item 1</li>
			<li>List-item 2</li>
			<li>List-item 3</li>
		</ul>
	</aside>
</div>

You may also like:

Adam

User imageAdam is a web developer, student, and entrepreneur based in London, UK. He has 10 years experience in the web development industry using PHP, HTML, CSS, MySQL. Adam is also a keen skier, snowboarder, squash player, and football fan.

comments powered by Disqus