Part 1: Pseudo-Classes
Learn about CSS pseudo-class selectors.
Pseudo-classes
Pseudo-class selectors are predefined keywords that define the state of an element or target a child element. They occur pretty frequently, and we can see them in action when a colon follows an element. An example of this is the :hover
selector:
a:hover {
/* Hover is a pseudo-class! */
}
Note: The
:hover
selector selects elements when you mouse over them.
Common pseudo-class selectors
Listed below are some of the most common pseudo-classes grouped into the following categories: state, validation, structural, and relational.
Let’s take a look at them!
State pseudo class selectors
A state pseudo-class selector is used when the user is expected to complete particular actions, such as clicking or hovering over a link.
The :link
selector represents a link that hasn’t been visited yet. It matches all unvisited a
links, as long as they have an href
attribute.
a:link {
color: blue;
}
Styles defined by the :link
pseudo-class selector are overridden by any subsequent state pseudo-class selector (:active
, :hover
, or :visited
). So, it’s always best to put the :link
rule before the rest.
The :visited
selector selects all links that have been visited in the current browser session.
a:visited {
color: red;
}
The :hover
selector is used whenever the user’s cursor hovers over a link without clicking it. We can apply styles to this state with the :hover
pseudo-class.
In the example below, a
elements change to orange
when hovered over:
a:hover {
color: orange;
cursor: pointer;
}
The :active
selector selects a link when it’s being activated. This could be when it’s clicked, tapped (on a touchscreen), or even when tabbed to (as in a navigation item) on a keyboard.
a:active {
color: pink;
}
Example
Get hands-on with 1400+ tech skills courses.