1364

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.

10
  • 32
    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
    Commented Jul 19, 2011 at 8:50
  • 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): w3.org/TR/2002/WD-css-style-attr-20020515
    – Kato
    Commented Aug 10, 2011 at 17:37
  • 1
    possible duplicate of Is is possible to create inline pseudo styles?
    – Synetech
    Commented Nov 20, 2012 at 2:20
  • 40
    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
    Commented Jul 26, 2013 at 23:08
  • 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
    Commented Feb 21, 2020 at 6:39

25 Answers 25

740

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.

30
  • 5
    you can add css classes in javascript Commented Jun 23, 2009 at 15:13
  • 289
    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 E.
    Commented Nov 1, 2010 at 2:24
  • 32
    @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. Commented Oct 4, 2011 at 16:30
  • 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
    Commented Oct 21, 2011 at 21:24
  • 16
    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!!! =) Commented Feb 22, 2013 at 2:35
643

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

7
  • 22
    that's smart! Works for a background color hover effect as well <div onMouseOver="this.style.backgroundColor='#F8F8F8'" onMouseOut="this.style.backgroundColor='#FFFFFF'"> ...
    – mxro
    Commented Jan 8, 2013 at 3:52
  • Firstly, thank you, and then is there a smart trick for writing li.selected {...} in an inline style as well?
    – Solace
    Commented Aug 9, 2014 at 17:25
  • 66
    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
    Commented Dec 22, 2014 at 1:40
  • and you can remove a hover background color from being applied using onMouseOver="this.style.backgroundColor='transparent'", same for onmouseout
    – Jay Rizzi
    Commented Apr 28, 2015 at 14:29
  • 8
    I needed to do this for an email and it worked. Thank you! This actually solves the question, unlike the accepted answer. Commented Jul 20, 2018 at 16:53
65

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 .

14
  • 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. Commented Mar 27, 2012 at 12:18
  • 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.
    – user379888
    Commented Mar 27, 2012 at 12:27
  • 4
    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 Commented Mar 27, 2012 at 12:45
  • 5
    In case anyone comes across this answer, the answerer posted a question about this feature here: stackoverflow.com/questions/9884182/…
    – BoltClock
    Commented Jun 27, 2012 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. Commented Jul 4, 2013 at 23:00
58

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

0
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>
2
  • 4
    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)
    – merwok
    Commented May 31, 2012 at 3:00
  • @ÉricAraujo: Then wrap this all content under a <html> </html> tag
    – user379888
    Commented Mar 2, 2017 at 14:18
42

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.

12
  • 4
    Thank you. That's a great answer, I think this answer must be as solution. Commented Sep 1, 2015 at 6:17
  • 111
    No, OP said they wanted it in inline CSS inside the HTML style attribute.
    – red-o-alf
    Commented Apr 5, 2016 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
    Commented Apr 7, 2016 at 2:24
  • 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
    Commented Nov 2, 2018 at 13:59
  • 4
    The question asked about inline style for a reason, you didn't use inline style.
    – shinzou
    Commented Dec 9, 2018 at 15:56
34

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"
2
  • 3
    Since this answer has been edited down, it now appears to be completely irrelevant to the original question...
    – Bill
    Commented Jul 4, 2016 at 15:28
  • 1
    Wow, that's thinking outside the box... I love it!
    – theglossy1
    Commented Nov 29, 2016 at 4:52
32

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'
}

1
  • This! Thanks - only thing that worked for me. Simple solution to the question. Commented May 4, 2022 at 16:56
15

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;"
1
  • 2
    that should be the best answer Commented Dec 17, 2018 at 8:56
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>
1
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>

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

1
  • 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
    Commented Oct 8, 2012 at 14:45
7

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>

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.

1
  • 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 Commented Jun 23, 2009 at 15:16
4

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.

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!

3

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.

2
  • 1
    Please avoid posting duplicate answers Commented Jan 7, 2020 at 2: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
    Commented Jan 7, 2020 at 7:10
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.

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

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)

0

There is no builtin way to do this, but you can make JavaScript convert certain style attributes into CSS rules.

const init_inline_style_pseudo = options => {
    const {
        root = document,
        dynamic = true,
        class_id = true,
    } = options ?? {};

    const unique_name_key = Symbol();
    let stylesheet = document.createElement("style");
    document.head.append(stylesheet);
    stylesheet = stylesheet.sheet;

    const get_elements = function*(...nodes) {
        for (const node of nodes) {
            for (const attr of node.attributes ?? []) {
                if (attr.name.match(/^style./)) {
                    yield node;
                }
            }
            if (node.children) {
                yield* get_elements(...node.children);
            }
        }
    }

    const process_el = (el, attr_name) => {
        let attrs;
        if (attr_name) {
            attrs = [[attr_name, attr_name.match(/^style(.+)$/)?.[1]]];
        }
        else {
            attrs = [...el.attributes].map(attr => [attr.name, attr.name.match(/^style(.+)$/)?.[1]]);
        }
        attrs = attrs.filter(([attr_name, pseudo]) => pseudo);
        if (!attrs.length) {
            return;
        }

        let unique_name = el[unique_name_key];
        if (!unique_name) {
            unique_name = el[unique_name_key] = `el-${crypto.randomUUID()}`;
            if (class_id) {
                el.classList.add(unique_name);
            }
            else {
                el.setAttribute(unique_name, "");
            }
        }

        for (const [attr_name, pseudo] of attrs) {
            const selector = class_id ? `.${unique_name}${pseudo}` : `[${unique_name}]${pseudo}`;

            const existing_rule_index = [...stylesheet.cssRules].findIndex(r => r.selectorText == selector);
            if (existing_rule_index >= 0) {
                stylesheet.deleteRule(existing_rule_index);
            }
            
            const rules = el.getAttribute(attr_name);
            if (!rules) {
                continue;
            }

            const rule_index = stylesheet.insertRule(`${selector} { ${rules} }`);
            const rule = stylesheet.cssRules[rule_index];
            for (const [prop_name, prop_value] of rule.styleMap.entries()) {
                rule.style.setProperty(prop_name, prop_value.toString(), "important");
            }
        }
    };

    get_elements(root).forEach(el => process_el(el));

    if (dynamic) {
        new MutationObserver(mutations => {
            for (const mutation of mutations) {
                switch (mutation.type) {
                    case "childList":
                        get_elements(...mutation.addedNodes).forEach(el => process_el(el));
                        break;
                    case "attributes":
                        if (mutation.attributeName.match(/^style./)) {
                            process_el(mutation.target, mutation.attributeName);
                        }
                        break;
                }
            }
        }).observe(root, {
            subtree: true,
            childList: true,
            attributes: true,
        });
    }
};
init_inline_style_pseudo();

// dynamic HTML example
document.getElementById("add-link").addEventListener("click", function(e) {
    const color = document.getElementById("link-color").value;
    const bg_color = "#"+((1<<24) - parseInt(color.slice(1), 16)).toString(16).padStart(6, "0");
    const li = document.createElement("li");
    li.setAttribute("style:hover", `background: ${bg_color}`);
    const a = document.createElement("a");
    a.href = color;
    a.setAttribute("style:hover", `color: ${color}`);
    a.textContent = `Link ${color}`;
    li.append(a)
    document.getElementById("links").append(li);

    document.getElementById("link-color").value = "#" + Math.floor((Math.random() * (1 << 24))).toString(16).padStart(6, "0");
});
document.getElementById("link-color").value = "#00FF00";
<main>
  <ol id="links">
    <li>
      <a
        href="#one"
        style="color: green"
        style:hover="color: red"
        style:active="font-weight: bold"
      >Link one</a>
    </li>
    <li>
      <a
        href="#two"
        style:hover="color: cyan"
        style:active="font-weight: bold"
      >Link two</a>
    </li>
  </ol>
  <input
    id="link-color"
    type="color"
    style:focus="outline: 4px solid black"
  >
  <button id="add-link">Add</button>

  <div
    id="one"
    style:target="text-transform: uppercase; font-weight: bold;"
    style:target::before="content: '<'"
    style:target::after="content: '>'"
  >one</div>
  <div
    id="two"
    style:target="text-transform: uppercase; font-weight: bold;"
    style:target::before="content: '>'"
    style:target::after="content: '<'"
  >two</div>

  <label>
    <input
      type="checkbox"
      style:checked+*="display: inline"
      style:checked+*+*="display: none"
      style~*="color: magenta"
    >
    <span style="display: none">Checked</span>
    <span style="display: inline">Unhecked</span>
  </label>
</main>

This works even with dynamic HTML and you can even use other selectors as long they make a valid attribute name.

This is not useful for HTML in emails as this requires JavaScript, but could be useful for prototyping. I wouldn't use this in production either.

1
  • Yes it's a bit too much outside of the scope of this question.
    – NVRM
    Commented Aug 31 at 16:24
-1

You can just use an inline stylesheet statement like this:

<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
0
-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.

-4

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 */
1
  • Surely you don't need external sheets, just use the style tag. Commented May 4, 2017 at 6:12
-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).

Not the answer you're looking for? Browse other questions tagged or ask your own question.