CSS hover property


The :hover pseudo-class in CSS is used to apply styles to an element when the mouse pointer is placed over it. It is commonly used to create interactive effects for links, buttons, and other clickable elements, enhancing the user experience by providing visual feedback.

Syntax

element:hover { /* styles */ }
  • element: The selector targets the specific element(s) you want to style on hover.

How It Works

  1. Basic Usage:

    • You apply styles to an element when the user hovers over it with the mouse.
    a:hover { color: red; text-decoration: underline; }
    • In this example, when the user hovers over a link (<a>), the text color changes to red, and the text is underlined.
  2. Interactive Elements:

    • The :hover pseudo-class can be applied to a variety of elements, such as buttons, images, and divs, to create interactive effects.
    button:hover { background-color: blue; color: white; }
    • In this case, when the user hovers over a button, the background color changes to blue and the text color changes to white.

Example

HTML

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hover Example</title> <style> .box { width: 100px; height: 100px; background-color: green; transition: background-color 0.3s ease; } .box:hover { background-color: yellow; transform: scale(1.1); } </style> </head> <body> <div class="box"></div> </body> </html>

Explanation:

  • .box:

    • Defines a div with a 100px by 100px size and a green background color.
    • The transition property smoothly animates the background color change over 0.3s.
  • .box:hover:

    • When the user hovers over the div, its background color changes to yellow and the transform property scales it up by 1.1 times.

Important Points

  1. Default Behavior:

    • The :hover pseudo-class does not affect the default behavior of the element; it only applies additional styles when the element is hovered.
  2. Use with Other Pseudo-Classes:

    • :hover can be combined with other pseudo-classes or elements, such as :focus, :active, and :visited, to create more complex interactions.
    a:hover, a:focus { color: blue; }
    • In this case, both hovering over and focusing on a link will change its color to blue.
  3. JavaScript Interaction:

    • While :hover is a CSS-only feature, you can also use JavaScript to programmatically add or remove classes or styles based on hover-like interactions.
  4. Performance Considerations:

    • Using :hover with complex animations or transformations can impact performance, especially on low-end devices. The transition property can help to manage these effects smoothly.