Using CSS Pseudo-Elements

In the 2.1 CSS Specification, there are four different pseudo-elements available to use. These are :after, :before, :first-letter and :first-line. Here’s a quick description of each one.

:after

:after inserts generated content at the end of the element’s content.

:before

Funnily enough, :before inserts generated content before the content of the element.

:first-letter

:first-letter styles the first letter of any given element. If you wanted all level 3 headings to have a larger first-letter, you would use it like this

h3:first-letter {
  font-size:150%;
}

:first-line

Similar to :first-letter but this styles all of the first line of the element

p:first-line {
  color:red;
}

As a quick example of using a pseudo-element, let’s display a little pdf icon in front of any link that opens a pdf document, a nice visual clue for the user. Our simple example would look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<p>Use this <a href="somedoc.pdf" rel="pdf">link</a> to view our latest prices.</p>
</body>
</html>

Notice that the link has been given a ‘rel’ attribute with a value of ‘pdf’. We can then target that link with an exact attribute selector. Combined with the :before pseudo-element, the css would look like this:

a {
text-decoration:none;
}
a:hover {
text-decoration:underline;
}
a[rel="pdf"]:before {
content:url(pdf.gif);
}

You can see a very simple example here

Feed IconFollow me on Twitter





6 Responses to “Using CSS Pseudo-Elements”

  1. Dugg :)

  2. hahaha! Thanks Scott :D

  3. Nice and clear explanation – so simple even I could follow it! Now… which ones of those pesky browsers lets you actually use these things?!

  4. As far as I can make out, IE doesn’t support :before and :after (not sure about IE8 though) but :first-line and :first-letter seem to be ok.
    Anybody using a decent browser should be fine :)

  5. Here’s a great list of browser support for a whole load of CSS goodness.

    http://www.quirksmode.org/css/contents.html

  6. Very handy link that Kit.
    Cheers :)

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">