This fragment is about to be reported (you'll remain on this page):

You can enter a comment to clarify the mistake if you would like to:

Using CSS after pseudoclass to clear floats

Using CSS after pseudoclass to clear floats

It's quite often to have floating blocks and it almost equally often you need to clear them (i.e. let the following content start after their end). However, it's not always possible to insert <div style="clear: both"></div> all around your page's code simply because you might have no control over its generation.

Luckly for us, major browsers support a nifty CSS 2 selector – :after pseudoclass. And we can use it to simulate a trailing clearing <div> just like shown before.

Here's the sample code:

xml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <style>
    img { float: left; }
    div:after { content: ""; display: block; clear: left; }

    p { background: red; }
    div { background: gray; }
    </style>
  </head>
  <body>
    <img src="pic.jpg" />
    <p>This is some text.</p>

    <div style="clear: both"></div>

    <div>
      <img src="pic.jpg" />
      <p>This is some text.</p>
    </div>
  </body>
</html>
http://proger.i-forge.net/Компьютер/HTML/[20120417] Using CSS after pseudoclass to clear floats.png

And here's what it produces – paragraphs have red background and divs have white. The first div isn't cleared so its content overflows the bottom border while the second successfully clears the contained left-floating image.

Padding will also work if applied to the last div.

Comments RSS20

Your name: Your homepage:

Text & signature markup:You can use UverseWiki markup. In short: **bold**, //italic//, %%code%%, ((URL link)), >inline quote, <[ multiline quote ]>.

Humans! Please enter "J" here: (or turn JavaScript on for automatic verification)
Subscribe by e-mail (manage):
Ctrl+Enter »