Advanced CSS – Part #6
Pseudo-elements are used to add special effects to some html elements.
Pseudo-elements are very much like pseudo-classes. The syntax for pseudo-elements is like pseudo-classes:
1
selector:pseudo-element {property:value;}
We can also use class selectors with our pseudo-elements:
1
selector.class:pseudo-element {property:value;}
Pseudo-elements
Since pseudo-elements exist to give some html elements some flair, we have a few special pseudo-elements that we need to be familiar with.
:first-line
As the name implies, this pseudo-element adds special styles to the first line of text. We can only use this pseudo-element with block-level elements (see Display Property for more details).
1 2 3 4 5 6 7
p:first-line {
color:#ff9300;
font-style:italic;
}
The above code would make the first line of text color turn to atomicpages orange and then change the first line of text to be italic. There are, however, certain properties that are not allowed when using the :first-line property. We can use the following:
- all font properties
- color
- all background properties
- text-decoration
- clear
- text-transform
- letter-spacing
- word-spacing
- vertical-align
- line-height
These are the only properties that are valid to use with the :first-line pseudo-element!
:first-letter
This pseudo-element applies unique styles to the first letter of text. Consider the following code:
1 2 3 4 5 6 7 8 9
p.a:first-letter {
background:#fff url("images/fancy_a.gif") no-repeat;
border:1px solid #ff9300;
margin-left:25px;
}
This will load the first image of all p elements with the class “a” so:
1 2 3
<p class="a">very fancy image at the beginning of this makes this
sentence seem much more grandiloquent that it really is!</p>
This fancy_a.gif will also have a border of 1px which is solid and atomicpages orange and will have a left margin of 25px.
Like the :first-line pseudo-element, there are restrictions on which properties can be used with this pseudo-element.
- all font properties
- color
- all background properties
- text-decoration
- clear
- text-transform
- letter-spacing
- word-spacing
- vertical-align
- line-height
- margin properties
- padding properties
- float
:before
This pseudo-element is used to insert content before and element is rendered by the browser. Consider the following code:
1
span:before {background:#fff url("images/fancy_a.gif") no-repeat;}
This is saying that before every span element there will be that fancy “A” that we define earlier in this tutorial.
:after
This pseudo-element is used to insert content after and element is rendered by the browser. Consider the following code:
1
h4:after {background:#fff url("images/fancy_b.gif") no-repeat;}
This is saying that after every h4 element there will be that fancy “B”.
Now what does that accomplish? Nothing very significant in this case but you can click on the green download button to see these pseudo-elements in action!

pseudo-elements.zip
Size: 7.76 KB
