In CSS, pseudo-classes are used to define special states of an element. These allow you to apply styles to elements when they are in certain conditions, like when a user interacts with them. In this article, we’ll cover three common pseudo-classes: :hover, :focus, and :nth-child.
The :hover
pseudo-class is used to apply styles to an element when the user hovers their mouse over it. It is commonly used with links, buttons, and other interactive elements to provide visual feedback on interaction.
For example, to change the color of a link when the user hovers over it:
a:hover { color: red; }
In this case, when the user hovers over any <a>
tag (link), its color will change to red.
The :focus
pseudo-class is used to style elements that have received focus, typically from keyboard navigation or user interaction. This is commonly used for form elements like text inputs and buttons to show which element is currently selected.
For example, to change the border color of a text input when it receives focus:
input:focus { border-color: blue; }
In this example, when the user clicks into or tabs to an <input>
field, its border color will change to blue, indicating that it has focus.
The :nth-child
pseudo-class is used to select elements based on their position within a parent element. It allows you to target specific children of an element, such as every other element or the first element in a group.
For example, to style every odd-numbered list item in a list:
li:nth-child(odd) { background-color: lightgray; }
This rule will apply a light gray background to every odd <li>
element inside a parent, such as a <ul>
or <ol>
.
Similarly, you can target every even-numbered element with :nth-child(even)
:
li:nth-child(even) { background-color: lightblue; }
This rule will apply a light blue background to every even <li>
element in the list.
You can also use :nth-child
to target a specific child element. For example, to target the 3rd child of a parent element:
li:nth-child(3) { font-weight: bold; }
This will apply bold text to the third <li>
element within its parent.
Here’s a summary of the pseudo-classes we’ve covered:
Pseudo-classes provide powerful ways to target elements based on their state or position, enhancing the interactivity and user experience of your website. By using :hover
, :focus
, and :nth-child
effectively, you can create visually engaging and accessible interfaces.