How to write a:hover in inline CSS?

1,351,499

Solution 1

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.

Solution 2

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').

Solution 3

You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't .

Solution 4

You can't do exactly what you're describing, since a:hover is part of the selector, not the CSS rules. A stylesheet has two components:

selector {rules}

Inline styles only have rules; the selector is implicit to be the current element.

The selector is an expressive language that describes a set of criteria to match elements in an XML-like document.

However, you can get close, because a style set can technically go almost anywhere:

<html>
  <style>
    #uniqueid:hover {do:something;}
  </style>
  <a id="uniqueid">hello</a>
</html>

Solution 5

I'm extremely late contributing to this, however I was sad to see no one suggested this, if you actually require inline code, this is possible to do. I needed it for some hover buttons, the method is this:

.hover-item {
	background-color: #FFF;
}

.hover-item:hover {
	background-color: inherit;
}
<a style="background-color: red;">
	<div class="hover-item">
		Content
	</div>
</a

In this case, the inline code: "background-color: red;" is the switch colour on hover, put the colour you need into there and then this solution works. I realise this may not be the perfect solution in terms of compatibility however this works if it is absolutely needed.

Share:
1,351,499
Amr Elgarhy
Author by

Amr Elgarhy

Updated on July 09, 2022

Comments

  • Amr Elgarhy
    Amr Elgarhy almost 2 years

    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.

    • providence
      providence almost 13 years
      Embedding html into blogging applications also often requires exclusive use of inline styles. Especially if you are embedding the html through a third party client and have no access to the user's themes.
    • Kato
      Kato almost 13 years
      There is a proposed CSS standard for this; no idea what sort of browser support it might have (hint: they could be using the custom tags like -moz, etc): w3.org/TR/2002/WD-css-style-attr-20020515
    • Synetech
      Synetech over 11 years
    • ElBel
      ElBel almost 11 years
      Oh come on. Sometimes you're just building a landing page prototype and you don't want to have to go fork the stylesheets or create a new template branch or whatever just to test out whether the green button works better. Sheesh.
    • Tofandel
      Tofandel almost 10 years
      @FriendlyNeighborhoodIdiot This page is 13 years old, the draft has been abandoned since.
    • Nathan
      Nathan over 4 years
      I see none of the answers respond to HTML email use case. In fact, for that case, you can indeed use standard (embedded) CSS. Not every email client may accept it, but many do.
  • Amr Elgarhy
    Amr Elgarhy about 15 years
    the problem that i can't do so, i am sending a javascript file in http response and js creates the html code and the css inline, and can't send another file. i know 100% that its better to use style sheet files
  • Pradeep Kumar
    Pradeep Kumar about 15 years
    you can add css classes in javascript
  • Amr Elgarhy
    Amr Elgarhy about 15 years
    @Jonathan Fingland how? can you remind me with s short sample?
  • Amr Elgarhy
    Amr Elgarhy about 15 years
    While this is a work around but it seams a very good answer for me and the best answer if really its not possible to write inline hover
  • Pradeep Kumar
    Pradeep Kumar about 15 years
    also see hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript for a more comprehensive solution (could be optimized though)
  • seanmonstar
    seanmonstar about 15 years
    alternatively, you could write the onmouseover and onmouseout attributes to change style like hover.
  • user3346601
    user3346601 about 15 years
    That idea will fortunately be dropped. (See lists.w3.org/Archives/Public/www-style/2009Jun/0341.html , under "Abandoned Working Drafts".)
  • Simon East
    Simon East over 13 years
    There are other circumstances where inline CSS is the only option - such as HTML emails (eg. Gmail ignores CSS unless it is inline). Unfortunately with Javascript stripped in most email clients as well I have not yet found a way of adding :hover effects.
  • Pradeep Kumar
    Pradeep Kumar over 13 years
    @Simon, perhaps your situation requires a new/different question. The OP question was not related to emails which have a very different set of restrictions.
  • Pradeep Kumar
    Pradeep Kumar over 12 years
    @Kato while that is a great link, and I really wish it worked, sadly it does not. Just to confirm, I tested using the syntax style="{color:green;} :hover { color: red; }" and firefox managed to color the link green, but ignored the hover. Chrome ignored both. Continued testing would be pretty pointless.
  • rineez
    rineez over 12 years
    That's right, No browser seem to have started supporting that syntax yet. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." :-) I would love to see that implemented though, as I am also working with news letters now.
  • Kato
    Kato over 12 years
    I didn't state it as a working solution. I stated is wasn't "entirely" correct to say there is no inline equivalent and that pseudo selectors have no meaning outside stylesheets. How is that inappropriate?
  • Amr Elgarhy
    Amr Elgarhy over 12 years
    all other answers said that it is not possible, but yours show that it is possible, your answer is different, I am testing it.
  • Admin
    Admin over 12 years
    Actually I needed the same thing as you do. I tested it but it did not worked for me. But I still think it should work as its by w3c.
  • Admin
    Admin over 12 years
    Sorry, I just checked the date of the article. Its 10 years old. So there is no guarantee that it should work. If it does, please do tell me too.
  • Amr Elgarhy
    Amr Elgarhy over 12 years
    I tested this: <a href="http://www.w3.org/" style="{color: #900} :link {background: #ff0} :visited {background: #fff} :hover {outline: thin red solid} :active {background: #00f}">...</a> But it didn't work
  • Amr Elgarhy
    Amr Elgarhy over 12 years
    check this stackoverflow.com/a/5293299/20126 what I understood that any pseudo code is not valid inside attributes
  • Admin
    Admin over 12 years
    Thanks for adding that to my knowledge.
  • Lena Schimmel
    Lena Schimmel about 12 years
    Tested in Firefox 12 and works. Doesn't work in Chromium 18, but doesn't harm neither.
  • Lena Schimmel
    Lena Schimmel about 12 years
    But: Does not work within GMail-Signatures, which was one of the initial reasons to do this.
  • merwok
    merwok about 12 years
    Actually you can’t: “HTML permits any number of STYLE elements in the HEAD section of a document.” (w3.org/TR/html4/present/styles.html#edef-STYLE)
  • Kevin LaBranche
    Kevin LaBranche about 12 years
    @jonathan-fingland ROFL when I read the short and long answer and simultaneously shamed me into doing it right in the first place. I didn't even have to read beyond "you shouldn't". Well played, Well played. :-)
  • BoltClock
    BoltClock about 12 years
    @Lena Schimmel: I'm pretty sure that's not supposed to work in any browser, period. If it worked in Firefox 12, it was probably a bug, because it doesn't work in Firefox 13.
  • BoltClock
    BoltClock about 12 years
    In case anyone comes across this answer, the answerer posted a question about this feature here: stackoverflow.com/questions/9884182/…
  • Chris
    Chris over 11 years
    @Derek in case still of interest / for anyone else reading: "~/" (tilde forward slash) is a server-side reference to the application root in asp.net web applications. (The application root may be a sub-folder of course). It's use here would not have been correct, hence the reason the answer has been edited since you asked the question (I suspect).
  • Adam Grant
    Adam Grant over 11 years
    While it is generally (99.999% of the time) a good idea not to use inline styles, there are some scenarios where this is important. I came to this question because users will be picking their own colors from a color picker, which will paint the background of table cells that color, but only when hovering over the parent row. Since we're using an MVC framework, we'd like to generate this directly in the HTML. Would it really be easier/better to use classes for this?
  • Shane
    Shane over 11 years
    I agree with Simon, inline workarounds are always needed for corner cases and it's not necessarily good to discourage researching them.
  • mxro
    mxro over 11 years
    that's smart! Works for a background color hover effect as well <div onMouseOver="this.style.backgroundColor='#F8F8F8'" onMouseOut="this.style.backgroundColor='#FFFFFF'"> ...
  • Miguel Angelo
    Miguel Angelo over 11 years
    Why long answer is You shouldn't... you... you shouldn't generalize. I was trying to send e-mail messages with html, but guess what... gmail removes all style tags, all external style references, and all scripts. So... is there any way to style hover color of links inside emails sent to gmail? Hope it does... hope is the last to die!!! =)
  • Pradeep Kumar
    Pradeep Kumar over 11 years
    @ajkochanowicz sorry for the late reply here,but you'd be wanting to add the style classes via javascript as noted in the first Edit section.
  • Pradeep Kumar
    Pradeep Kumar over 11 years
    @MiguelAngelo Sorry to hear about your troubles, but HTML emails are notoriously finicky. Stuff that looks fine in Thunderbird will be awful in Yahoo's web email client. Gmail will be fine, but Outlook will barf. Email is probably the biggest reason for a "you shouldn't". Your best bet is to treat everything like HTML 3, and not get too fancy with special effects.
  • Ilya Streltsyn
    Ilya Streltsyn almost 11 years
    More accurate to say, you could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't.
  • Rudie
    Rudie almost 11 years
    There's always a "head section", even if there's no <head>.
  • Ji ZHANG
    Ji ZHANG almost 11 years
    Very interesting draft, why it's not effective is beyond me.
  • Joel
    Joel over 10 years
    There is a . missing in this answer.
  • Admin
    Admin about 10 years
    @Simon I think the best solution would be to have <style> tags for hover events (and don't even go near JS) If the client doesn't support <style> then they simply don't get the effect. Pretty graceful if you ask me.
  • Catskul
    Catskul almost 10 years
    Works for me in Chrome Version 35.0.1916.114
  • Solace
    Solace almost 10 years
    Firstly, thank you, and then is there a smart trick for writing li.selected {...} in an inline style as well?
  • Eduard Luca
    Eduard Luca over 9 years
    No, no, no. I refuse to believe that you shouldn't. OK, say you have some kind of ads, and want to let the publisher or advertiser configure the hover state of the ad in a JSON file. You clearly can't use CSS classes there, so the only 2 options are: create a <style> element where you can use :hover or do the whole thing with JS (onmouseover). There you have a use case where you should do this.
  • Manachi
    Manachi over 9 years
    Have to laugh at this being seen as 'clever' :) It's hard to imagine that some people weren't around when this was the prominent/only way you could achieve this effect. Or worse still, to have an 'image' and have to swap out the image, just to give the 'hover' effect. Makes me feel old! But suffice to say, it does answer the OP's question :)
  • BoltClock
    BoltClock over 9 years
    @Kato: At the time you posted that comment, that draft was almost a decade old, and was already superseded by a newer revision where that information has clearly been removed. While the working group may have toyed with the idea of introducing selectors into inline styles in the distant past, that idea clearly fell out of favor. On top of that, not only is it inappropriate to cite unstable drafts as canon, it's even more so to cite an old draft as canon where newer revisions already exist. This seems to be a common mistake people make.
  • BoltClock
    BoltClock over 9 years
    @Kato: But in your defense, the W3C TRs don't make it very clear that a certain revision is no longer the latest one beyond the revision date at the very top of the page. So just something for you to keep in mind in the future - you can reach the latest revision of a W3C document by going to the top and clicking where it says "Latest version". And never call something a "standard" unless there is evidence that it has in fact been standardized.
  • Farzher
    Farzher over 9 years
    Long answer: you shouldn't Don't forget that some of us are hackers, and an inline style tag might be our only way to exploit a system (;
  • Jay Rizzi
    Jay Rizzi about 9 years
    and you can remove a hover background color from being applied using onMouseOver="this.style.backgroundColor='transparent'", same for onmouseout
  • cesoid
    cesoid about 9 years
    You should always add a selector in a style sheet for every one-off style? I agree that you should minimize even using one-off styles in the first place, but I'm not sure why you should take the style of a single exception to styling rules and move it where you have to go hunt it down... even if you just have to look up to the top of the file. I know some very good programmers who disagree with that.
  • cesoid
    cesoid about 9 years
    Also, I'd argue that a good explanation renders statements about what you should and shouldn't do unnecessary, whereas statements about what you should and shouldn't do don't explain much of anything.
  • Rowe Morehouse
    Rowe Morehouse about 9 years
    Actually, you can, and you should if you want too.
  • Eric Castro
    Eric Castro about 9 years
    I have to agree with Manachi on this one. This is like a flashback to 90s geocities javascript ;P
  • Vedmant
    Vedmant almost 9 years
    RE: Long answer: you shouldn't: What about if I need to generate a lot of different tags with different hover colors and all this data is pulled from DB, generating whole stylesheet just to render one page is not a good solution. And what if this content after being generated have to be stored in DB somewhere in post content, so it will need always <style></style> block for each of individual other block. Looks very bad I think.
  • Hovhannes Sargsyan
    Hovhannes Sargsyan almost 9 years
    Thank you. That's a great answer, I think this answer must be as solution.
  • lukesrw
    lukesrw almost 9 years
    Thanks sarhov, hopefully people see this if they need it.
  • Redoman
    Redoman about 8 years
    No, OP said they wanted it in inline CSS inside the HTML style attribute.
  • lukesrw
    lukesrw about 8 years
    I know, jj_- however this method allows you to put only a few lines into the CSS and use it over and over in many places, many people (including myself) have found this to be a helpful alternative.
  • Hayko Koryun
    Hayko Koryun about 8 years
    this should be the actual answer, with a slight modification: don't set any of the colours in the style, just the rule to inherit from parent when hovered, and then set the two colours inline.
  • jeffdill2
    jeffdill2 about 8 years
    This still will not work for Gmail as the non-inline styles will be stripped out.
  • Bill
    Bill almost 8 years
    Since this answer has been edited down, it now appears to be completely irrelevant to the original question...
  • Maverick976
    Maverick976 almost 8 years
    This answer helped me with my own solution to using dynamic hover colors. Very clever, thanks.
  • vhs
    vhs over 7 years
    Works on my machine. Thanks!
  • theglossy1
    theglossy1 over 7 years
    Wow, that's thinking outside the box... I love it!
  • John
    John over 7 years
    I think this is a very elegant solution - and it has just helped me out - sometimes writing styles inline needs to be done.
  • Admin
    Admin over 7 years
    @ÉricAraujo: Then wrap this all content under a <html> </html> tag
  • Dmitri Zaitsev
    Dmitri Zaitsev about 7 years
    Surely you don't need external sheets, just use the style tag.
  • technoTarek
    technoTarek almost 7 years
    Here's another reasonable use case for inline style: background-image. Think of a site where the background image is used to style each blog's post, based on image assigned to that specific post. This is done dynamically. Using an inline background-image makes a lot more sense than dynamically building your CSS file, which would be a nightmare and inefficient.
  • Pradeep Kumar
    Pradeep Kumar almost 7 years
    @technoTarek See developer.mozilla.org/en/docs/Web/CSS/attr You could use an attribute like data-background-image="whatever.jpg" on the item and then in your css use background-image: attr(data-background-image url)
  • technoTarek
    technoTarek almost 7 years
    @JonathanFingland Mindblown. But then again...here's looking to the future: caniuse.com/#feat=css3-attr
  • theUtherSide
    theUtherSide almost 6 years
    I needed to do this for an email and it worked. Thank you! This actually solves the question, unlike the accepted answer.
  • wcndave
    wcndave over 5 years
    This is just the "normal" way to do it, which everyone was saying is the right way. However it's not an inline way, which was the OP original request.
  • shinzou
    shinzou over 5 years
    The question asked about inline style for a reason, you didn't use inline style.
  • Vladislav Guleaev
    Vladislav Guleaev over 5 years
    that should be the best answer
  • Stephen R
    Stephen R over 4 years
    "There are other circumstances where inline CSS is the only option - such as HTML emails...." Thank God you can't do this stuff in emails. All we need is all-singing, all-dancing spam
  • flash
    flash over 4 years
    I don't see why people say this is the elegant solution at all. This feels like a solution to something else (reusability of the .hover-items perhaps??). If you're still writing stylesheet :hover, why not just put it on the a and be done with it? Someone please help me understand - anyone?
  • lukesrw
    lukesrw over 4 years
    @flash This is useful if you've got a dynamic background-color property (for instance, if the colours are coming from a database), or if the aim is to allow more flexibility in HTML without updating CSS. You're allowing the HTML to define a colour, while leaving the transition to CSS.
  • Simas Joneliunas
    Simas Joneliunas over 4 years
    Please avoid posting duplicate answers
  • Quentin
    Quentin over 4 years
    "You could do it at some point in the past" — No, you couldn't. There was a draft specification but nothing ever implemented it.
  • Quentin
    Quentin over 4 years
    None of these approaches solve the problem expressed in the question. You can't use JS in an HTML formatted email at all, and the other approach you suggest uses classes which is explicitly ruled out.
  • run_the_race
    run_the_race about 4 years
    When styling emails, one can't avoid it.
  • brianc
    brianc over 3 years
    "you shouldn't" is a nice thought but sometimes it is the only option.The question specifically requested a solution for this problem, not an opinion. I run into this often enough where selected styles (such as font color) need to be set dynamically by the user and an external stylesheet is not feasible.
  • Anurag
    Anurag about 3 years
    This is the actual answer to the question asked. The accepted answer is best practice.
  • Jp Serame
    Jp Serame almost 3 years
    In the year 2021, this isn't working anymore. Hopefully someone can point to a possible solution.
  • Someone_who_likes_SE
    Someone_who_likes_SE over 2 years
    ​​​​​​​​​​​​​​​But it's not an inline style...
  • Ash90
    Ash90 over 2 years
    Sorry, I meant to say inline stylesheet. I have corrected my answer.
  • Pete Shilling
    Pete Shilling over 2 years
    Love this solution!
  • Victor Yan
    Victor Yan over 2 years
    The best solution so far
  • tswaters
    tswaters over 2 years
    This is the way.
  • mamena tech
    mamena tech about 2 years
    best solution, love it, thanks
  • Emma Earl Kent
    Emma Earl Kent about 2 years
    This! Thanks - only thing that worked for me. Simple solution to the question.
  • Igor Gunin
    Igor Gunin about 2 years
    One example of where "you shouldn't" just does not work is emails. You need to send an email with a particular style and absolutely every email mailbox breaks CSS classes to some extent.