Two columns using CSS (look, no tables)

closeThis post was published 4 years 11 months 22 days ago. Therefore, it may well be out of date. Do not reply on the contents of this post being accurate.

On the whole tables are not a good idea for page layout. CSS is considered much better and basic stuff is quite easy to learn (if you’re familiar with the <div> tag).

In this post I’ll give you a short tutorial to show how to create two colums without using tables…

Why?

Well, why not?

No, that’s not the answer. The answer is, because tables should really only be used for displaying tabular data.

The code in the right column works basically like this…

  • The width of the first <div> is set to 40% of the width available to it in the browser
  • The first <div> is also set to float left, that is, it’s aligned left and also allows the following <div> to float (or flow) with the first <div> rather than beneath it
  • The second <div> therefore takes its position next to the first <div>, 40% away from the left-hand side and level with the first <div>

How?

Code needed (no tables)

<div>
<div style="float: left; width: 40%">
<h2>Why?</h2>
<p>Well, why not?</p>
<p>No, that's not the answer… </p>
</div>
<div style="float: left;">
<h2>How?</h2>
<p>Code needed (no tables)</p>
</div>
</div>

I’m using two columns on my 404 page (that is, any page that doesn’t exist). You can see it via this wrong link. (NB. you wont see this in Internet Explorer. Why? Because Internet Explorer obfuscates error messages. But of course, you could try it in Firefox or Safari where it works as intended).

To make these columns work properly you need to cancel the process. You can do this by clearing the float, but there’s a hack that I found at positioniseverything.net, using a class called .clearfix which, as you can see, allows you to stop using two columns and makes available the full width of the browser (and importantly, is browser independent).

The code, copied from positioniseverything.net, is detailed below:

CSS code for your stylesheet

.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

HTML code for your web page

class="clearfix"

This entry was posted in WebDev. Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>