CSS Pseudo Classes
Styling based on external factors
Note
Let us try hovering and clicking the button below.
We quickly notice that the background color of the button changes when our mouse pointer hovers over the element. Additionally, there is a shadow like gray outline when we click the button. How is this possible? How can we tell CSS to modify the styling of an element bases on external factors like the mouse position, the history of the navigator or the status of the content?
Turns out, CSS has a feature that gives us all of these styling options: pseudo classes. These classes allow us to style an element based on some external factors and lets us define a specific state of the element. For example, it can be used to style elements when the user mouses over it or differentiate between previously visited and unvisited elements.
Code example: general
selector:pseudo-class-name {property: value;}
We specify the pseudo-class after the selector separated by a colon symbol. We have many pseudo-classes available to us, and the MDN web docs link below contains a full list of them.
Read more on MDN
Pseudo-classes
Code example: hover
The :hover pseudo-class is procced when a pointing device hovers
over an element. :hover works well for computers with dedicated
mice, but can be hard to get right for touchscreens.
div {background-color: blue;width: 32rem;height: 32rem;}div:hover {background-color: red;}
produces (try hovering over the blue square below)
Code example: focus
The :focus pseudo-class is procced when an element is clicked on or
is selected with the tab key. This pseudo-class is intended for
typical form input elements, and might have an unexpected behavior for
other types of elements.
Accessibility
Do not remove the browser default :focus styles purely for
aesthetics reasons as they are intended to help with the accessibility
of our web sites.
button {background-color: blue;width: 32rem;height: 32rem;border: 1em solid;color: rgb(17, 17, 17);}button:focus {background-color: red;border-color: black;}
produces (try clicking the blue square below)