Open In App

How to Write a:hover in Inline CSS?

Last Updated : 11 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The :hover pseudo-selector in CSS enables you to modify the style of elements when a user hovers their mouse over them. This selector is widely used to improve user experience by adding visual feedback on elements like buttons, links, images, or any interactive items on a webpage.

For the :hover effect to work consistently across all elements and browsers, ensure your document includes a <!DOCTYPE html> declaration for full compatibility.

Example 1: Hover Effects with JavaScript (Inline Event Handlers)s

Although you cannot directly use :hover in inline CSS, you can simulate a hover effect with JavaScript by utilizing the onmouseover and onmouseout event handlers. Here’s how you can do it:

html
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            text-align: center;
        }

        a {
            text-decoration: none;
            color: green;
        }
    </style>
</head>

<body>
    <h2>a:hover in inline CSS</h2>
  
    <a href="#" onMouseOver="this.style.color='red'"
        onMouseOut="this.style.color='green'">
        GeeksforGeeks
    </a>
</body>

</html>

Output

output

Explanation:

  • Inline CSS is used for the initial color (color: green) applied to the link.
  • The onMouseOver and onMouseOut attributes in the anchor (<a>) tag are JavaScript event handlers that change the color of the link when the user hovers over it and when the mouse moves away.

Example 2: Hover Effects Using CSS

While JavaScript is a useful way to manipulate styles, the recommended approach for hover effects is to use CSS. You can apply the :hover pseudo-class in internal or external CSS.

html
<!DOCTYPE html>
<html>

<head>
    <style>
        body {
            text-align: center;
        }

        a {
            text-decoration: none;
            color: green;
        }

        /* CSS hover effect */
        a:hover {
            color: red;
        }
    </style>
</head>

<body>
    <h2>a:hover in inline CSS</h2>
  
    <a href="#">GeeksforGeeks</a>
</body>

</html>

Output

output

Explanation:

  • This example uses CSS to apply the hover effect. When the user hovers over the link (<a>), the text color changes to red.
  • The a:hover selector is the correct way to handle hover effects using CSS, separating the presentation layer (CSS) from the structure (HTML).

Conclusion

In conclusion, while inline CSS cannot directly apply the :hover pseudo-class, JavaScript can simulate hover effects. However, using CSS (internal or external) is the best practice for hover effects, as it ensures cleaner, more maintainable code and better separation between structure and presentation.


Article Tags :

Similar Reads