CSS :hover
selector is used to apply CSS styles on an element when you hover over it. As soon as you take the mouse pointer away from the element, these CSS styles are removed from it.
The :hover
selector is not just limited to the links, you can use it on any HTML element that you want.
In the following example, the p:hover
selector sets a yellow background color to the <p>
element as soon as you take the mouse over it.
Example:
p:hover{ background-color: yellow; }
You can apply as many CSS properties to the element as you want while hovering over it.
In the following example, we are changing the background-color, padding, and font color of each paragraph when we hover over it. You can also add other properties if you want:
Example:
p:hover{ background-color: yellow; padding: 10px; color: red; }
You can also add the same hover effect to multiple elements by separating each element by a comma. See the example below:
Example:
p:hover, h2:hover, li:hover{ background-color: yellow; }
In all the examples that we have discussed so far, we have only applied CSS styles to the same element that we are hovering over.
But we can also apply styles to one element while hovering over the other. This is the functionality which is used in tooltips.
See this example:
Example:
h2:hover + p{ display: block; } p{ display: none; padding: 20px; background: yellow; }
CSS Syntax
The syntax of the :hover
selector is as follows:
:hover{ CSS Styles; }
Browser Support
The number in each cell of the table specifies the first version of the browser that fully supports the :hover
selector.
Selector | |||||
:hover | 4.0 | 7.0 | 2.0 | 3.1 | 9.6 |