What are Pseudo-classes?
A pseudo-class also known as Pseudo-selector is used to define a special state of an element.
For example, it can be used to:
- Style an element when a user mouses over it
- Style visited and unvisited links differently
- Style an element when it gets focus
Anchor Pseudo-classes
Links can be displayed in different ways:
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
Pseudo-classes and HTML Classes
Pseudo-classes can be combined with HTML classes like :hover
pseudo selector.
Ex.
div:hover {
background-color: blue;
}
Hover on
An example of using the :hover pseudo-class on a
element is shown above👆. On Hover the div's background color will change to blue.The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first child of another element.
Ex.
p:first-child {
color: blue;
}
In above Example, the selector matches any
element that is the first child of any element and it will turn it into blue color.
The :lang Pseudo-class
The :lang pseudo-class allows you to define special rules for different languages.
In the example below, :lang defines the quotation marks for elements with lang="no".
Ex.
<html>
<head>
<style>
q:lang(no) {
quotes: "~" "~";
}
</style>
</head>
<body>
<p>First text <q lang="no">
A quote in a paragraph
</q> Last text.</p>
</body>
</html>
Output ->
::before and ::after Pseudo-Selector
::before
The ::before selector inserts something before the content of each selected element(s).
Syntax:
::before {
css declarations;
}
Ex.
<!DOCTYPE html>
<html>
<head>
<style>
p::before {
content: "Read this -";
background-color: yellow;
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Demo of the ::before selector</h1>
<p>My name is Donald</p>
<p>I live in Ducksburg</p>
</body>
</html>
Remember to put a content property bcoz it's important!
Output ->
::after
The ::after selector inserts something after the content of each selected element(s).
Syntax:
::after {
css declarations;
}
Ex.
<!DOCTYPE html>
<html>
<head>
<style>
p::after {
content: " - Remember this";
background-color: yellow;
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Demo of the ::after selector</h1>
<p>My name is Donald</p>
<p>I live in Ducksburg</p>
</body>
</html>
Output ->
Other CSS Pseudo-Classes:
Did you find this Article helpful?
Give it a Heart and comment your thoughts!
References:
w3schools CSS Pseudo-Classes
Top comments (0)