CSS selectors play a key role in styling an HTML element. Selectors are used to select the HTML elements that you want to apply styles to on a web page; this can either be a class, ID, or attribute.
CSS offers several pseudo-classes to style elements that can help differentiate between various element states. The pseudo-class is a keyword combined with a selector to specify a special state of the selected element(s) in CSS.
For example, the :hover
keyword, when combined with a CSS selector, can be used to style an element when the user’s pointer hovers over it.
In this shot, we will mainly focus on the CSS Hover selector, which is a User Action Pseudo-class selector, which styles an HTML element when the user hovers over the element with a cursor. Hover selectors are visible until the user stops hovering over the element with their cursor.
The syntax for the :hover
selector is as follows:
css-selector:hover {
// CSS rules
}
The CSS selector can either be a class, ID, or HTML attribute.
The :hover
keyword specifies states for which the styles of the CSS rules will be used.
For example:
.group:hover{
color:purple;
}
When the user hovers over the group
class, the color is set to change to purple
.
:hover
selectorThere are various ways in which the hover
selector can be used:
In the example above, the color of the h1
element will change when the pointer hovers over it.
In the example above, the image changes the shape when the user’s pointer hovers over it by changing the value of the border-radius
in the hover state.
In the example above, the hover state is set to have a transition effect of adding a border-bottom
to each navbar item.
In the example above, the background of the button changes when the pointer hovers over it.
As a user action pseudo-class selector, there are some limitations on how the styles apply to various devices.
Mouse: The :hover
styling will show when the mouse hovers over an element.
Mobile devices: The :hover
state will get triggered on click/touch even though there’s no pointer event.
Keyboard: The :hover
styling will not be triggered because there’s no pointer event.