1320

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • 11
    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): http://www.w3.org/TR/2002/WD-css-style-attr-20020515 – Kato Aug 10 '11 at 17:37
  • 31
    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. – providence Jul 19 '11 at 08:50
  • 1
    possible duplicate of [Is is possible to create inline pseudo styles?](http://stackoverflow.com/questions/986618/is-is-possible-to-create-inline-pseudo-styles) – Synetech Nov 20 '12 at 02:20
  • 36
    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. – ElBel Jul 26 '13 at 23:08
  • 2
    @FriendlyNeighborhoodIdiot This page is 13 years old, the draft has been abandoned since. – Tofandel Sep 14 '14 at 21:40
  • 2
    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. – Nathan Feb 21 '20 at 06:39
  • Whatever solution you pick, don’t forget to also provide a `:focus` style, which is very important for keyboard and screen reader users. – Andy Jul 05 '22 at 15:32

24 Answers24

722

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.

Giampaolo Ferradini
  • 529
  • 1
  • 6
  • 17
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • 1
    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 – Amr Elgarhy Jun 23 '09 at 15:11
  • 5
    you can add css classes in javascript – Jonathan Fingland Jun 23 '09 at 15:13
  • 1
    @Jonathan Fingland how? can you remind me with s short sample? – Amr Elgarhy Jun 23 '09 at 15:14
  • see http://www.quirksmode.org/dom/changess.html for details on adding css classes. (read all the way to the bottom) – Jonathan Fingland Jun 23 '09 at 15:19
  • also see http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript for a more comprehensive solution (could be optimized though) – Jonathan Fingland Jun 23 '09 at 15:20
  • alternatively, you could write the onmouseover and onmouseout attributes to change style like hover. – seanmonstar Jun 23 '09 at 16:21
  • 275
    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. – Simon East Nov 01 '10 at 02:24
  • @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. – Jonathan Fingland Nov 01 '10 at 13:52
  • 31
    @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. – Jonathan Fingland Oct 04 '11 at 16:30
  • 3
    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. – rineez Oct 13 '11 at 05:25
  • 10
    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? – Kato Oct 21 '11 at 21:24
  • @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. :-) – Kevin LaBranche Jun 21 '12 at 22:22
  • 2
    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? – Adam Grant Nov 12 '12 at 14:41
  • 2
    I agree with Simon, inline workarounds are always needed for corner cases and it's not necessarily good to discourage researching them. – Shane Jan 01 '13 at 00:10
  • 13
    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!!! =) – Miguel Angelo Feb 22 '13 at 02:35
  • @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. – Jonathan Fingland Mar 21 '13 at 03:55
  • 2
    @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. – Jonathan Fingland Mar 21 '13 at 03:58
  • 1
    There's always a "head section", even if there's no ``. – Rudie Sep 01 '13 at 18:35
  • @Simon I think the best solution would be to have –  Apr 03 '14 at 22:53
  • 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 ` – Eduard Luca Nov 28 '14 at 09:43
  • 2
    @Kato: At the time you posted that comment, that draft was almost a decade old, and was already superseded by a [newer revision](http://www.w3.org/TR/2010/CR-css-style-attr-20101012) 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 Jan 26 '15 at 08:01
  • 1
    @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. – BoltClock Jan 26 '15 at 08:09
  • 4
    `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 (; – Farzher Mar 17 '15 at 15:11
  • 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 May 02 '15 at 17:50
  • 1
    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. – cesoid May 02 '15 at 18:05
  • 3
    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 block for each of individual other block. Looks very bad I think. – Vedmant Jul 02 '15 at 17:29
  • 1
    "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 – Stephen R Oct 24 '19 at 17:05
  • When styling emails, one can't avoid it. – run_the_race Jun 08 '20 at 09:51
  • 3
    "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. – brianc Feb 11 '21 at 23:18
  • 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. – Igor Gunin Jun 07 '22 at 02:41
620

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

Gangani Roshan
  • 583
  • 1
  • 8
  • 25
Alex S
  • 25,241
  • 18
  • 52
  • 63
  • 20
    that's smart! Works for a background color hover effect as well `
    ...`
    – mxro Jan 08 '13 at 03:52
  • Firstly, thank you, and then is there a smart trick for writing `li.selected {...}` in an inline style as well? – Solace Aug 09 '14 at 17:25
  • 61
    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 :) – Manachi Dec 22 '14 at 01:40
  • and you can remove a hover background color from being applied using onMouseOver="this.style.backgroundColor='transparent'", same for onmouseout – Jay Rizzi Apr 28 '15 at 14:29
  • 7
    I needed to do this for an email and it worked. Thank you! This actually solves the question, unlike the accepted answer. – theUtherSide Jul 20 '18 at 16:53
  • This is the actual answer to the question asked. The accepted answer is best practice. – Anurag Jun 17 '21 at 23:07
  • I live this solution for the eventual situation. – kissumisha Feb 08 '23 at 11:34
63

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 .

  • 3
    all other answers said that it is not possible, but yours show that it is possible, your answer is different, I am testing it. – Amr Elgarhy Mar 27 '12 at 12:18
  • 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. –  Mar 27 '12 at 12:25
  • 2
    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. –  Mar 27 '12 at 12:27
  • 4
    I tested this: `...` But it didn't work – Amr Elgarhy Mar 27 '12 at 12:45
  • check this http://stackoverflow.com/a/5293299/20126 what I understood that any pseudo code is not valid inside attributes – Amr Elgarhy Mar 27 '12 at 12:49
  • Thanks for adding that to my knowledge. –  Mar 27 '12 at 17:23
  • Tested in Firefox 12 and works. Doesn't work in Chromium 18, but doesn't harm neither. – Lena Schimmel May 15 '12 at 18:56
  • But: Does not work within GMail-Signatures, which was one of the initial reasons to do this. – Lena Schimmel May 15 '12 at 19:11
  • @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 Jun 27 '12 at 16:18
  • 5
    In case anyone comes across this answer, the answerer posted a question about this feature here: http://stackoverflow.com/questions/9884182/why-dont-we-import-css-in-a-div – BoltClock Jun 27 '12 at 16:18
  • 11
    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](http://www.w3.org/TR/css-style-attr/#syntax). – Ilya Streltsyn Jul 04 '13 at 23:00
  • Very interesting draft, why it's not effective is beyond me. – Jerry Sep 26 '13 at 07:25
  • Works for me in Chrome Version 35.0.1916.114 – Catskul Jul 22 '14 at 14:09
  • "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 Jan 07 '20 at 07:09
52

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>
Community
  • 1
  • 1
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • 4
    Actually you can’t: “HTML permits any number of STYLE elements in the HEAD section of a document.” (http://www.w3.org/TR/html4/present/styles.html#edef-STYLE) – merwok May 31 '12 at 03:00
  • 5
    Works on my machine. Thanks! – vhs Nov 06 '16 at 21:24
  • @ÉricAraujo: Then wrap this all content under a ` ` tag –  Mar 02 '17 at 14:18
44

While it appears to be impossible to define a hover-rule inline, you can define the value of styles inline using a CSS variable:

:hover {
  color: var(--hover-color);
}
<a style="--hover-color: green">
    Library
</a>

Consider using an attribute or a class in addition to the selector (e.g., [hover-color]:hover) to allow coexistence with other low specificity hover color changing rules (from, e.g., a CSS reset or some elements using the default style).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Simon
  • 1,172
  • 12
  • 21
43

If you actually require inline code, this is possible to do. I needed it for some hover buttons, and 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. Use the colour you need 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lukesrw
  • 1,692
  • 1
  • 14
  • 20
  • 4
    Thank you. That's a great answer, I think this answer must be as solution. – Hovhannes Sargsyan Sep 01 '15 at 06:17
  • 1
    Thanks sarhov, hopefully people see this if they need it. – lukesrw Sep 01 '15 at 19:01
  • 108
    No, OP said they wanted it *in inline CSS inside the HTML style attribute*. – Redoman Apr 05 '16 at 21:15
  • 3
    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. – lukesrw Apr 07 '16 at 02:24
  • 2
    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. – Hayko Koryun Jun 07 '16 at 09:07
  • 1
    This still will not work for Gmail as the non-inline styles will be stripped out. – jeffdill2 Jun 10 '16 at 14:23
  • This answer helped me with my own solution to using dynamic hover colors. Very clever, thanks. – Maverick976 Sep 23 '16 at 16:38
  • I think this is a very elegant solution - and it has just helped me out - sometimes writing styles inline needs to be done. – John Dec 12 '16 at 11:04
  • 10
    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. – wcndave Nov 02 '18 at 13:59
  • 4
    The question asked about inline style for a reason, you didn't use inline style. – shinzou Dec 09 '18 at 15:56
  • 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? – flash Dec 04 '19 at 08:12
  • 2
    @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. – lukesrw Dec 04 '19 at 10:31
33

Using JavaScript:

a) Adding inline style

document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');

b) or a bit harder method - adding "mouseover"

document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };

Note: multi-word styles (i.e.font-size) in JavaScript are written together:

element.style.fontSize="12px"
tkazik
  • 919
  • 3
  • 12
  • 27
T.Todua
  • 53,146
  • 19
  • 236
  • 237
29

This is the best code example:

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 onmouseover="this.style.color='#0F0'"
 onmouseout="this.style.color='#00F'">
   Library
</a>

Moderator Suggestion: Keep your separation of concerns.

HTML

<a
 style="color:blue;text-decoration: underline;background: white;"
 href="http://aashwin.com/index.php/education/library/"
 class="lib-link">
   Library
</a>

JS

const libLink = document.getElementsByClassName("lib-link")[0];
// The array 0 assumes there is only one of these links,
// you would have to loop or use event delegation for multiples
// but we won't go into that here
libLink.onmouseover = function () {
  this.style.color='#0F0'
}
libLink.onmouseout = function () {
  this.style.color='#00F'
}
Eric Hodonsky
  • 5,617
  • 4
  • 26
  • 36
Jay Bharat
  • 691
  • 7
  • 6
14

Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version).

For now, your best bet is probably to just define a style block directly above the link you want to style:

<style type="text/css">
    .myLinkClass:hover {text-decoration:underline;}
</style>
<a href="/foo" class="myLinkClass">Foo!</a>
SystemParadox
  • 8,203
  • 5
  • 49
  • 57
brettkelly
  • 27,655
  • 8
  • 56
  • 72
  • 5
    That idea will fortunately be dropped. (See http://lists.w3.org/Archives/Public/www-style/2009Jun/0341.html , under "Abandoned Working Drafts".) – Ms2ger Jun 23 '09 at 17:18
11

As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:

style="cursor: pointer;"
dakab
  • 5,379
  • 9
  • 43
  • 67
citronic
  • 9,868
  • 14
  • 51
  • 74
9

You can do this. But not in inline styles. You can use onmouseover and onmouseout events:

<div style="background: #333; padding: 10px; cursor: pointer"
   onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">
      Hover on me!
</div>
8
<style>a:hover { }</style>
<a href="/">Go Home</a>

Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.

Joel
  • 19,175
  • 2
  • 63
  • 83
  • 2
    @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). – Chris Oct 08 '12 at 14:45
5

There is no way to do this. Your options are to use a JavaScript or a CSS block.

Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.

CrazyMatt
  • 501
  • 1
  • 4
  • 12
m_vitaly
  • 11,856
  • 5
  • 47
  • 63
5

According to your comments, you're sending a JavaScript file anyway. Do the rollover in JavaScript. jQuery's $.hover() method makes it easy, as does every other JavaScript wrapper. It's not too hard in straight JavaScript either.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vineel Shah
  • 960
  • 6
  • 14
  • 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 – Amr Elgarhy Jun 23 '09 at 15:16
5

It's not exactly inline CSS, but it is inline.

<a href="abc.html" onMouseOver="this.style.color='#0F0'" 
onMouseOut="this.style.color='#00F'">Text</a>
AStombaugh
  • 2,930
  • 5
  • 13
  • 31
Sir XtC
  • 166
  • 1
  • 9
4

You can write code in various type.

First I can write this

HTML

<a href="https://www.google.com/" onMouseOver="this.style.color='red'"
        onMouseOut="this.style.color='blue'" class="one">Hello siraj</a>

CSS

.one {
    text-decoration: none;
}

You can try another way:

HTML

<a href="https://www.google.com/" class="one">Hello siraj</a>

CSS

.one {
    text-decoration: none;
}

.one:hover {
    color: blue;
}

.one:active {
    color: red;
}

You can also try hover in jQuery:

JavaScript

$(document).ready(function() {
  $("p").hover(function() {
    $(this).css("background-color", "yellow");
    }, function() {
      $(this).css("background-color", "pink");
  });
});

HTML

<p>Hover the mouse pointer over this paragraph.</p>

In this code you have three functions in jQuery. First you ready a function which is the basic of a function of jQuery. Then secondly, you have a hover function in this function. When you hover a pointer to the text, the color will be changed and then next when you release the pointer to the text, it will be the different color, and this is the third function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Siraj Ahmed
  • 128
  • 2
  • 6
  • 1
    Please avoid posting duplicate answers – Simas Joneliunas Jan 07 '20 at 02:04
  • 1
    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. – Quentin Jan 07 '20 at 07:10
4

I just figured out a different solution.

My issue: I have an <a> tag around some slides/main content viewer as well as <a> tags in the footer. I want them to go to the same place in IE, so the whole paragraph would be underlined onHover, even though they're not links: the slide as a whole is a link. IE doesn't know the difference. I also have some actual links in my footer that do need the underline and color change onHover. I thought I would have to put styles inline with the footer tags to make the color change, but advice from above suggests that this is impossible.

Solution: I gave the footer links two different classes, and my problem was solved. I was able to have the onHover color change in one class, have the slides onHover have no color change/underline, and still able to have the external HREFS in the footer and the slides at the same time!

CrazyMatt
  • 501
  • 1
  • 4
  • 12
Liz
  • 41
  • 1
1

I agree with shadow. You could use the onmouseover and onmouseout event to change the CSS via JavaScript.

And don't say people need to have JavaScript activated. It's only a style issue, so it doesn't matter if there are some visitors without JavaScript ;) Although most of Web 2.0 works with JavaScript. See Facebook for example (lots of JavaScript) or Myspace.

mrid
  • 5,782
  • 5
  • 28
  • 71
Jaysn
  • 53
  • 2
1

So this isn't quite what the user was looking for, but I found this question searching for an answer and came up with something sort of related. I had a bunch of repeating elements that needed a new color/hover for a tab within them. I use handlebars, which is key to my solution, but other templateing languages may also work.

I defined some colors and passed them into the handlebars template for each element. At the top of the template I defined a style tag, and put in my custom class and hover color.

<style type="text/css">
    .{{chart.type}}-tab-hover:hover {
        background-color: {{chart.chartPrimaryHighlight}} !important;
    }
</style>

Then I used the style in the template:

<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
   Payouts
</span>

You may not need the !important

webhound
  • 339
  • 1
  • 4
  • 13
1

While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.

Approach CSS only

CSS


/* Set your parent color for the inherit property */
.sidebar {
  color: green;
}

/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
  color: inherit
}

.list-item a:hover {
  color: inherit
}

/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
  color: inherit !important;
}

Then your markup will be somewhat like:

Markup

<nav class="sidebar">
  <ul>
    <li class="list-item">
      <a
        href="/foo"
        class="dynamic-hover-color"
        style="color: #{{category.color}};"
      >
        Category
      </a>
    </li>
  </ul>
</nav>

I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)

Alexis Duran
  • 620
  • 14
  • 28
-1

You can just use an inline stylesheet statement like this:

<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
Ash90
  • 77
  • 7
-3

You can use the pseudo-class a:hover in external style sheets only. Therefore I recommend using an external style sheet. The code is:

a:hover {color:#FF00FF;}   /* Mouse-over link */
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-3

You can do id by adding a class, but never inline.

<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>

It is two lines, but you can reuse the class everywhere.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bug
  • 342
  • 1
  • 10
-4

My problem was that I'm building a website which uses a lot of image-icons that have to be swapped by a different image on hover (e.g. blue-ish images turn red-ish on hover). I produced the following solution for this:

.container div {
  width: 100px;
  height: 100px;
  background-size: 100px 100px;
}
.container:hover .withoutHover {
  display: none;
}
.container .withHover {
  display: none;
}
.container:hover .withHover {
  display: block;
}
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's).
</p>
<div class=container>
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>
</div>

I introduced a container containing the pair of images. The first is visible and the other is hidden (display:none). When hovering the container, the first becomes hidden (display:none) and the second shows up again (display:block).