In this chapter you will learn how to use advanced selectors in CSS3. We will use the built-in pseudo-class.
:first-child
This will select the first child element of its parent.
:last-child
This will select the last child element of its parent.
:only-child
This will select the only child element of its parent.
:first-of-type
This will select the first sibling element of its type.
:last-of-child
This will select the last sibling element of its type.
:only-of-type
This will select the only element of its type.
Let see the following example.
<div class='example-pseudoclass'> <h1>First Heading</h1> <p>First Content goes in here.</p> <h1>Second Heading</h1> <p>Second Content goes in here.</p> </div>Based on above example, if we want to change the color of h1 "First Heading" to red, we can use the following css.
h1:first-child{ color:red; } //Alternatively, we can use the :first-of-type as well, as it will apply to first element of h1. h1:first-of-type{ color:red; }
See Another example of using :last-of-child, in this time we going to use ul li tags.
<ul class='menu'> <li>Menu 1</li> <li>Menu 2</li> <li>Menu 3</li> <li>Menu 4</li> </ul> <style> //style the last li ul.menu li:last-child a { font-style:italic; } </style>
Element Based on Position in CSS3
In css3, you can have an option to select an element based on specific position. Those are the available pseudo-class you can use.
:nth-child()
This will select the nth-child of an element from its parent using the given value.
:nth-last-child()
This will select the nth-child of an element from its parent counting from the last one.
:nth-of-type()
This will select the nth sibling of an element of its type.
:nth-last-of-type()
This will select the nth sibling of an element of its type counting from the last one.
By combining above pseudo-class, there are couple ways to specify the position of an element.
-
Using a number to specify the position
The following css will select the second paragraph. You just need to enter the number value into the parameter.
<p>This is the first paragraph.</p> <p>This is the second paragraph.</p> <p>This is the third paragraph.</p> <style> p:nth-child(2){ font-weight:bold; } </style>
-
Using a keyword
You can use a keyword odd or even to apply the odd numbered row in the following paragraphs.
<p>This is the first paragraph.</p> <p>This is the second paragraph.</p> <p>This is the third paragraph.</p> <style> //This will make the first and third paragraph text become bold. p:nth-child(odd){ font-weight:bold; } </style>
-
Using a Recurring Sequence
You can use a recurring pattern with the following formula numbern
<style> //This will make the first and third paragraph text become bold. p:nth-child(3n + 2){ font-weight:bold; } </style>