[html] 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.

This question is related to html css inline-styles

The answer is


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:

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

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.


This is the best code example:

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

Moderator Suggestion: Keep your separation of concerns.

HTML

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

JS

_x000D_
_x000D_
const libLink = document.getElementsByClassName("lib-link")[0];_x000D_
// The array 0 assumes there is only one of these links,_x000D_
// you would have to loop or use event delegation for multiples_x000D_
// but we won't go into that here_x000D_
libLink.onmouseover = function () {_x000D_
  this.style.color='#0F0'_x000D_
}_x000D_
libLink.onmouseout = function () {_x000D_
  this.style.color='#00F'_x000D_
}
_x000D_
_x000D_
_x000D_


It's now possible with Hacss.


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>

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"


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>

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 */

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

_x000D_
_x000D_
<div style="background: #333; padding: 10px; cursor: pointer"_x000D_
   onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">_x000D_
      Hover on me!_x000D_
</div>
_x000D_
_x000D_
_x000D_


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


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:

_x000D_
_x000D_
.container div {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-size: 100px 100px;_x000D_
}_x000D_
.container:hover .withoutHover {_x000D_
  display: none;_x000D_
}_x000D_
.container .withHover {_x000D_
  display: none;_x000D_
}_x000D_
.container:hover .withHover {_x000D_
  display: block;_x000D_
}
_x000D_
<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)._x000D_
</p>_x000D_
<div class=container>_x000D_
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>_x000D_
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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


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


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 .


I had to avoid javascript, but could go with server side code.

so I generated an id, created a style block, generated the link with that id. Yes its valid HTML.

_x000D_
_x000D_
a {_x000D_
  text-decoration: none;_x000D_
  color: blue; _x000D_
}_x000D_
_x000D_
a:hover {_x000D_
  color: blue;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
  a[data-hover="rnd-id-123"] { color: green;  } _x000D_
  a[data-hover="rnd-id-123"]:hover { color: red; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-123">some link 1</a>_x000D_
_x000D_
<br>_x000D_
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
  a[data-hover="rnd-id-456"] { color: purple;  }_x000D_
  a[data-hover="rnd-id-456"]:hover { color: orange; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-456">some link 2</a>
_x000D_
_x000D_
_x000D_


you can write a 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

java script

$(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 a three function in jquery first you ready a function which is the basic of function of jquery then second you have a hover function in this function when you hover a pointer to the text the color will be changed and then the next the when you release the pointer to the text it will be the different color and this is the third function


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:

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

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


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>

2 lines but you can re-use the class everywhere.


This is pretty late in the game, but when would you use JavaScript in an HTML Email? For example, at the company I currently work for (rhymes with Abodee), we use the lowest common denominator for most email marketing campaigns – and JavaScript is just not being used. Ever. Unless you are referring to some kind of pre-processing.

As mentioned in a related post: "Lotus Notes, Mozilla Thunderbird, Outlook Express, and Windows Live Mail all seem to support some sort of JavaScript execution. Nothing else does."

Link to the article from which this was taken: [http://en.wikipedia.org/wiki/Comparison_of_e-mail_clients]

Also, how would hovering translate to mobile devices? That's why I like the answer from above:Long answer: you shouldn't.

If anyone has more insights into this subject, please feel free to correct me. Thank you.


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.


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)


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.


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.


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!


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;"