CSS pseudo class tip

By Paul McCarthy on 12 May 2009

Having contributed to a feature in last month’s Web Designer Magazine on great CSS secrets, we thought that the blog would be a great place to share the tip we came up with for clearing a float container without extra HTML mark up:

If a floated element is nested within a box that has a border or a background colour applied to it, the floated element will not force its container to stretch all the way down (mainly in standards compliant browsers).

To force the container box to enclose the floated div(s), it needs a ‘cleared’ element added after the last floated div. Rather than adding extra HTML mark up such as a clearing div or paragraph we can use CSS.

Using the pseudo-class :after it’s possible to add content at the end of an element with the following CSS commands:

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

Sometimes the container will also collapse in Internet Explorer. Unfortunately IE still doesn’t support the :after pseudo-class yet, so a simple declaration of height: 1% to the floated containing div will stop it from collapsing.

#id {
height:1%
}

Comments

  • how to make extra money commented on 15 May 2009 at 1:14 am

    It is not surprising that IE8 doesn’t even support :after. With still so many people using IE, I wonder if it is advantageous to use tools that won’t work. Cool tool though, can’t wait to use it.

  • sergi commented on 1 June 2009 at 7:01 pm

    i love simple, easy tips such as these. micro-learning, per se. thanks, and peace.

  • Stalin Selvam commented on 28 October 2009 at 3:16 pm

    I have a issue with IE-6 browser, getting a page printed, the content is running out of the right margin, not sticking to the div.

    I have used the media attribute of link tag, but still no result, Please can anybody suggest a work around or example to fix the issue..

Leave a comment

Required indicates required fields