How to Hover an Element Using Inline CSS

Subodh Poudel Feb 02, 2024
How to Hover an Element Using Inline CSS

This tutorial will introduce some methods to hover an element using inline CSS.

Use the onMouseOver and onMouseOut JavaScript Events to Create a Hover Effect Using Inline CSS

It is easy to apply the hover effect to an element while using an external CSS. For example, we can achieve it as shown as follows:

a{
 color:red;
}
a:hover{
 color:blue;
}

When we move the mouse to the a element, the red color changes to blue.

Here, we have used the :hover selector to select the element of our choice. But, we cannot write the :hover selector in inline CSS.

It is because the inline CSS only supports the styles, so it does not allow us to write the selector. But, we still can simulate the hover effect using inline CSS.

For that, we need to use the onMouseOver and onMouseOut JavaScript events. The onMouseOver event will execute when we move the mouse pointer onto an element.

Similarly, the onMouseOut event will execute when we move the mouse pointer off an element. We can use these events as an attribute of the anchor tag and set the color of the text.

For example, we can set a color when the mouse is moved onto the text using the onMouseOver event and set another color using the onMouseOut event. We can use the this keyword to invoke the style and color properties and then assign a color.

For example, create an anchor tag with the text Click Here and use the onMouseOver event as an attribute of the anchor tag. Set its value to this.style.color and give the color code #f00 and give the color code #000 to the onMouseOut event.

When we move the mouse onto the text Click Here, the color changes to red. And, when we remove the mouse from the text, the color changes to black.

In this way, we can use the JavaScript events to simulate the hover effect using the inline CSS.

Example Code:

<a href="#"
 onMouseOver="this.style.color='#f00'"
 onMouseOut="this.style.color='#000'" >
 Click Here
</a>
Subodh Poudel avatar Subodh Poudel avatar

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

LinkedIn

Related Article - CSS Inline