Pseudo-class
A CSS pseudo-class
is applied to style elements only when they are in a specific state (e.g., clicked, focused).
Pseudo-classes are used with a colon (:
) following the selectors, with :hover
being one of the most commonly used examples.
The hover pseudo-class applies styles when the mouse cursor hovers over an HTML element.
See the example below using the pseudo-class :hover
.
<html>
<body>
<button class="my-button">Hover Me</button>
</body>
</html>
.my-button {
display: inline-block;
padding: 10px 20px;
background-color: #0000ff;
color: #fff;
border-radius: 5px;
transition: background-color 0.3s ease;
border: none;
}
.my-button:hover {
background-color: #ff0000;
}
The above CSS code styles a button (<button>
) element with the class .my-button
.
The .my-button:hover
pseudo-class is used to change the background color to red when the mouse pointer hovers over the button.
Note that the transition
property adds a smooth animation to the property's changes.
In this example, a transition effect of 0.3s
is applied to the background-color
change, making the button's color change smoothly.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.