totn CSS

CSS :hover selector

This CSS tutorial explains how to use the CSS selector called :hover with syntax and examples.

Description

The CSS :hover selector allows you to target an element that the user hovers over with a cursor or mouse pointer.

Syntax

The syntax for the :active CSS selector is:

element:hover { style_properties }

Parameters or Arguments

element
The element to target when the user hovers over it.
style_properties
The CSS styles to apply to the element when the user is hovering over it.

Note

  • The :hover selector is a pseudo-class that allows you to target an element that the cursor or mouse pointer is hovering over.
  • It is difficult to apply the :hover selector on touch devices.
  • Starting in IE4, the :hover selector could only used with <a> tags. Since IE7, the :hover selector can be used with all elements.

Browser Compatibility

The CSS :hover selector has basic support with the following browsers:

  • Chrome
  • Firefox (Gecko)
  • Internet Explorer (IE)
  • Opera
  • Safari (WebKit)

Example

We will discuss the :hover selector below, exploring examples of how to use this selector in CSS to apply styling to an element that is hovered over.

With <a> tag

Let's look at a CSS :hover example where we apply the :hover selector to the <a> tag.

The CSS would look like this:

a:hover { color: white; background: blue; }

The HTML would look like this:

<div>
  <p>Here is a great site: <a href="https://www.checkyourmath.com/index.php">CheckYourMath.com</a></p>
</div>

When the <a> tag is not hovered over, it would look like this:

CSS

Then once you hover over the <a> tag, the :hover selector would style the <a> tag as follows:

CSS

In this :hover example, the link "CheckYourMath.com" will display as white text with a blue background only when it is hovered over with a cursor or mouse pointer.

With <div> tag

Let's look at a CSS :hover example where we apply the :hover selector to the <div> tag.

The CSS would look like this:

div:hover { background: yellow; }

The HTML would look like this:

<div>
  <p>TechOnTheNet.com has been providing helpful references, how-to's and FAQs since 2003. We focus on technologies such as Microsoft Access, Microsoft Excel, Microsoft Word, SQL, Oracle/PLSQL, MySQL, HTML, CSS, and the C Language.</p>
</div>
<div>
  <p>The information presented here is suitable for all programmers from beginner to expert. We hope you find this information useful and return to our site, as we expand our information base.</p>
</div>

When the <div> tag is not hovered over, it would look like this:

CSS

Then once you hover over one of the <div> tags, the :hover selector would style the <div> tag as follows:

CSS

In this :hover example, we hovered over the second <div> tag which caused the :hover selector to style the <div> with a yellow background.