First time visitor? The tutorials start here.

CSS Pseudo-elements

Pseudo-elements are very similar to pseudo-classes. So similar, in fact, that I’m not even sure why they consider them two different things.

All that really matters is understanding how they work, and that’s what I’m going to show you today.

Pseudo-elements you can use are:

  • :first-letter
  • :first-line
  • :before
  • :after

:first-letter

Syntax:

tagname.classname:first-letter

:first-letter does what you might expect. It affects the first letter within the targeted element.

Examples:

div.thisclass:first-letter {
	font-size:150%;
	color: #c00;
}
p.thatclass:first-letter {
	text-indent: -100000px;
	background:url(/images/O.gif);
}

…where “O.gif” is a graphic of a fancy letter O. Remember storybooks that like to start “Once upon a time” with a big, Old English O? That’s the effect this 2nd example will have.

:first-line

Syntax:

tagname.classname:first-line

:first-line also does what you might expect. It affects the first line within the targeted element. As soon as the text wraps around to the next line, it ceases to follow the :first-line rules you define for the first line.

Example:

p.myclass:first-line {
	font-variant: small-caps;
	font-weight: bold;
	color: #080;
}

The first line of the paragraph would look like this,
but once the text wraps, it would be normal.

:before and :after

These two pseudo-elements are used to insert what appears to be content, before or after the actual xHTML content.

Note: As of IE8, these still do not work in Internet Explorer.

Syntax:

tagname.classname:before

Examples:

Would you like quote images around quotations? Well, make those images in your favorite image editor, upload them, and use this CSS to insert them into blockquotes.

blockquote.yourclass:before { content: url(/images/openquote.gif); }
blockquote.yourclass:after { content: url(/images/closequote.gif); }

That refers to the <blockquote> tag, which I haven’t covered yet. <blockquote> tags should only be used for long quotes, not for mere indentation.

Another example:

p.myclass:before {
	content: '>  ';
	color: #f00;
	font-weight: bold;
}

The color and font-weight here will only affect the content that’s added via the :before pseudo-element. This example will insert a bold red > at the beginning of the paragraph.

The best way to learn is hands on, so play around with these on a practice page and see what you can come up with. If you have any questions, don’t hesitate to ask. 🙂

If you found this article useful, please spread the word:
Stumble it! Digg! Tweet it!



Questions or comments?

Please log in to post a comment. Sorry, but it prevents this from happening. If you're not registered yet, you can register here.