They are keywords that we can use in CSS to target elements in a particular state.
For example:
We use pseudo-classes by adding them to the end of our selector.
Syntax:
selector:pseudo-class {
property: value;
}
We can display links in different ways:
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: gray;
}
/* mouse over link */
a:hover {
color: yellow;
text-decoration: underline;
}
/* selected link */
a:active {
color: blue;
}
With :focus
Pseudo-class, we can style an element when it’s focused.
For example, we change the border of input when it’s focused.
form input:focus {
border: 4px dashed gray;
}
We can also change the style of input when it’s valid.
For example, when a user types in a valid email, the border’s color changes to blue.
form input:valid {
border: 4px solid blue;
}
The :first-child Pseudo-class can target the child of a parent element when it’s the first child inside the parent element.
<ul>
<li>Milk</li>
<li>Butter</li>
<li>Cheese</li>
</ul>
ul li:first-child {
border: 2px solid red;
}
Pseudo Elements allow us to inject dynamic content or style the content inside an element.
Syntax
The syntax of pseudo-elements:
selector::pseudo-element {
property: value;
}
List of Pseudo Elements:
The ::first-letter can add style to the first letter of a text.
p::first-letter {
color: red;
font-size: 30px;
}
::first-line adds a special style to the first line of a paragraph.
p::first-line {
font-weight: bold;
font-size: 1.2em;
}
::before pseudo-element can insert some content before the content of an element.
p::before {
content: url(smiley.gif);
}
::after can insert content after the content of an element.
p::after {
content: "...";
}
We can change the style of something when it’s selected with ::selection
p::selection {
background-color: red;
color: white;
}