A pseudo-class is used to define a special state of an element.
For example:
Let’s say we want to style the first <p>
in the article only.
<!-- 2 paragraphs in an article section -->
<article>
<p class="first">Lorem ipsum dolor sit amet.</p>
<p>Lorem ipsum dolor sit amet.</p>
</article>
Without Pseudo-class, we can define a class of the first <p>
:
/* Without using Pseudo-class Selectors */
/* You can specify first <p> by defining a class */
.first {
font-size: 140%;
font-style: italic;
}
By using Pseudo-class, we use :
to specify the relationship:
/* first-child inside article class */
article :first-child {
font-size: 140%;
font-style: italic;
}
However, this type of pseudo class selector is fragile. If we change the first element of article, the rule will break.
To address this issue, we can use first-of-type
selector
/* the first occurance of any type inside the article */
article :first-of-type {
font-size: 140%;
font-style: italic;
}
If we only want to style the first occurance of <p>
, we can be more specific:
/* the first occurance of <p> inside the article */
article p:first-of-type {
font-size: 140%;
font-style: italic;
}
Similarily, we can also apply the rule on last-of-type
:
/* the last occurance of <p> inside the article */
article p:last-of-type {
font-weight: bold;
}
/* the last child of <p> inside the article */
article p:last-child {
font-weight: bold;
}
To select specify rows of an unordered lists:
<!-- An unordered list containing 5 items -->
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
/* Select odd rows */
ul li:nth-child(odd) {
color: deeppink;
}
/* Select even rows */
ul li:nth-child(even) {
color: deeppink;
}
/* Select 3 multiple rows */
ul li:nth-child(3n) {
color: deeppink;
}