Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a:hover in inline CSS?

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.

How can I use a:hover in inline CSS inside the HTML style attribute?

E.g. you can't reliably use CSS classes in HTML emails.

like image 429
Amr Elgarhy Avatar asked Jun 23 '09 15:06

Amr Elgarhy


People also ask

Can we write hover in inline CSS?

Short answer: you can't. Long answer: you shouldn't. Give it a class name or an id and use stylesheets to apply the style. :hover is a pseudo-selector and, for CSS, only has meaning within the style sheet.

How do you use hover inline style?

It is called pseudo-selector and used to select all the elements when the user move mouse over the elements. It can be used on all the element. A <!

How do you write hover in CSS?

The :hover pseudo class in CSS selects elements when the mouse cursor is current over them. It's commonly associated with link ( <a> ) elements. It will turn green and have a line beneath and above it. In IE 6 and below, :hover used to only work on links, but in newer browsers, it works on any element.

How add hover inline CSS react?

Set the onMouseEnter and onMouseLeave props on the element. When the user hovers over or out of the element, update a state variable. Conditionally set inline styles on the element.


2 Answers

Short answer: you can't.

Long answer: you shouldn't.

Give it a class name or an id and use stylesheets to apply the style.

:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria).

Response to the OP's comments:

See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.

Also, don't forget, you can add links to external stylesheets if that's an option. For example,

<script type="text/javascript">   var link = document.createElement("link");   link.setAttribute("rel","stylesheet");   link.setAttribute("href","http://wherever.com/yourstylesheet.css");   var head = document.getElementsByTagName("head")[0];   head.appendChild(link); </script> 

Caution: the above assumes there is a head section.

like image 67
Jonathan Fingland Avatar answered Dec 01 '22 01:12

Jonathan Fingland


You can get the same effect by changing your styles with JavaScript in the onMouseOver and onMouseOut parameters, although it's extremely inefficient if you need to change more than one element:

<a href="abc.html"     onMouseOver="this.style.color='#0F0'"     onMouseOut="this.style.color='#00F'" >Text</a>

Also, I can't remember for sure if this works in this context. You may have to switch it with document.getElementById('idForLink').

like image 36
Alex S Avatar answered Nov 30 '22 23:11

Alex S