Using CSS3 pseudo-classess

You’ve most likely used pseudo-classes to style links before. From my experience, that’s been their most prevalent use with widest browser support: a:hover, a:visited, a:active, …. A pseudo class is added to an element selector in CSS to style elements on a page without having to add extra markup to your html. In essence, it gives you additional “hooks” on your markup that you can easily apply styles to.

Let’s take the :first-line pseudo-class as an example to get started.

Say you have the following html:

<p>CSS3 pseudo classes are so cool. You can learn how to use them really quickly. There are a lot of words in this paragraph so it's going to break over multiple lines.</p>

Our layout is narrow and such that this paragraph breaks into multiple lines when displayed in a browser. But you want to add emphasis to the first line of every paragraph by making it bold. Formerly, this would have been tedious. You could do it with a span around the first few words of each paragraph, but the precision of guessing how many words will appear on the first line is poor at best. And, as I mentioned early, doing it this way would force you to add to your markup specifically for styling (a span with a class defined with which you could target your CSS).

The HTML (the old way)
<p><span class="first_line">CSS3 pseudo classes are so</span> cool. You can learn how to use them really quickly. There are a lot of words in this paragraph so it's going to break over multiple lines.</p>

The CSS (the old way)
.first_line {font-weight:bold;}

 

Let’s make it easier using a CSS3 pseudo-class

Simply apply the :first-line pseudo-class to the p element in your css and the browser will do all the calculating/guessing of what text is on the first line for you.

p:first-line {font-weight: bold;}

Now, the first line of every paragraph will automatically be bold without having to add any additional markup to your page. Pretty simple. Pretty easy to use. Pretty powerful. You’re markup stays cleaner and your styling looks tight!

 

Other examples of pseudo-classes:

:after / :before
:first-child
:nth-child

Check out Mozilla Developers Network for a few more examples.

 

That’s it. Now go play around with it, figure out how it works. And make something amazing.

Leave a Reply

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