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.
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.
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').
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
.
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>
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.
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).
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"
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'
}
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>
Foo!
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;"
<style>a:hover { }</style>
Go Home
Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.
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>
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.
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.
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
Hello siraj
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.
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!
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>
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.
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
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)
You can just use an inline stylesheet statement like this:
<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
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 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.
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).
I have this structure with dynamic DIVs and all have the same class, since all are created automatically.
The problem here is that, the last of them prior to other DIV with other class, I would like to have his style as width:100% instead of width:50% as all others set by CSS.
Here's a sample:
<div class="awp_box awp_box_inner"></div>
<div class="awp_box awp_box_inner"></div>
<div class="awp_box awp_box_inner"></div>
<div class="awp_stock_container awp_sct" style="max-width: 400px !important;"></div>
So I only want to change that third DIV, which sometimes is the first and only one, other times is the second, other times is the fourth, etc...
I am usually good with CSS but this time I'm having a hard time finding a solution for this one.
Can someone please give me a hand here guiding me in the right track so I could put this working?
If I was correct in my question above then add this CSS
div.awp_box.awp_box_inner:nth-last-child(1) {
width: 100%;
}
Source: TutsPlus
Based on the comments, the following script could give you what you need.
$(document).ready(function(){
$('.awp_sct').prev().addClass('full');
});
It will add a class to the previous element of the .awp_sct.
DEMO
Hope someone can help me, I have an index.php setup and in the head I have a sideshow script set and this runs on all pages, and then in the portfolio.html (loads inside the index.php file when that page is called up) I have a gallery script.
My problem is when I click on a gallery image it opens up but behind this "header gallery" ...
image of what the problem is:
#pjumble is right about wanting to change the z-index. The problem you're having is probably related to the CSS Selectors priority.
When defining a CSS format you can write the selector statement in 3 basic ways and mix and match these as you please for advance selector definitions. Here are the 3 basic ways,
1.
Class's Looks something like this.
.class1
{
color:blue;
font-size: 24px;
background-color:red;
}
this is the Lowest priority
2.
ID's Looks something like this.
#id1
{
color:yellow;
font-size: 12px;
}
This is medium priority
3.
Tag's look something like this.
Div
{
color:green;
}
This one gets highest priority. This always seems counter intuitive to me. If I define and ID level format you think that would have priority over the one for that Tag name but it doesn't.
Here's and example of what I'm talking about.
So for an element like this
<Div id="id1" class="class1">
Text
</div>
The "Text" here is going to have a red background because "class1" is the only definition with a background-color.
But both "id1" and "class1" have definitions for font-size so the class definition is ignored and the id one is used making "Text" 12px.
Then all three definitions have "color" defined and the winner is "Div" making "Text" green.
so when you write your set up like this,
#lightbox a z-index of 100, .gallerylayer has a z-index of 1000
you have the right idea but your definition for ".gallerylayer" is a class and if the tag or id of that section of code has z-index defined, your class definition of z-index = 1000; will be ignored.
Just to make sure the definitions not ignored I'd give the tag that has class='gallerylayer' in it and add a id='somethingUnique' attribute and use that to define the z-index rule.
But the best way to check this is to use Firefox with the Firebug add-on and use the element selecting tool to see what styles are being apply and which are begin ignored on your page.
For more on selectors try looking here it should give you all the documentation you'll need.
hope this helps.
I want to link an entire <div>, but CSS2 does not support adding an href to a div (or span for that matter). My solution is to use the onClick property to add a link. Is this acceptable for modern browsers?
Example code:
<div class="frommage_box" id="about_frommage" onclick="location.href='#';">
<div class="frommage_textbox" id="ft_1"><p>who is Hawk Design?</p></div>
My test page is at http://www.designbyhawk.com/pixel. Updated daily.
Thanks for the help.
You don't need to do that. There's a perfectly simple and standards-compliant way to do this.
Block-level elements will by default take up the entire available width. a elements are not by default block-level, but you can make them so with display: block in CSS.
See this example (no Javascript!). You can click anywhere in the div to access the link, even though the link text doesn't take up the whole width. You just need to remove that p element and make it an a.
Attaching a click event handler to a <div> element will work for your users with JavaScript enabled.
If you're looking for a progressive enhancement solution, however, you'll want to stick with a <a> element.
It is acceptable, only it's not good for SEO.
Maybe you can make a <a> element act like a div? (settings it's style to display:block etc.)
It will work in every browser(even IE6). The only problem with this is that search engines probably won't fetch it since it's javascript. I see no other way to be able to make an entire div click-able though. Putting an "a" tag around it won't work in all browsers.
If all you're trying to achieve is a large clickable box, try setting the following CSS on an anchor:
a {
display: block;
padding: 10px;
width: 200px;
height: 50px;
}
HTML:
<div class='frommage_box'>
<a href='location.html'>CONTENT GOES HERE</a>
</div>
CSS:
.frommage_box a{
display:block;
height:100%;
}
By default block elements take up 100% width. We adjust the height to 100%. And this will allow spiders to crawl yoru page.
I have my current code:
#content img[src="/img/test.gif"] {
background-image:url(dark-img.png) !important;
}
From my understanding !important; overrides existing values?
Why isn't this overriding the current HTML image in place there? The background shows up, behind the HTML image.
I want it in front of the HTML image, is this possible using CSS or JS?
Edit: For what its worth, im making a userscript that will modify the existing style of the site. So I do not have direct access to the HTML image.
You don't need javascript for image replacement! As long as you can identify the image by a CSS selector, you can use CSS to do the trick.
See the solution here
http://www.audenaerde.org/csstricks.html#imagereplacecss
Here is the code using only css:
<img src="tiger.jpg"
style="padding: 150px 200px 0px 0px;
background: url('butterfly.jpg');
background-size:auto;
width:0px;
height: 0px;">
sets the image size to 0x0,
adds a border of the desired size (150x200), and
uses your image as a background-image to fill.
If you upvote this answer, give #RobAu's answer an upvote, too.
The replacement of an image in CSS can be done in several ways.
Each of them has some drawbacks (like semantics, seo, browsercompatibility,...)
On this link 9 (nine!) different techniques are discussed in a very good way :
http://css-tricks.com/css-image-replacement/
If you are interested in css in general : the whole site is worth a look.
The background-image property, when applied to an image, refers to (drum roll ... ) the background-image of the image. It will always be behind the image.
If you want the image to appear in front of the image, you are going to have to use two images, or another container with a background-image that covers the first image.
BTW, it is bad practice to rely on !important for overriding. It can also be ineffective since 1) it can't override declarations in an element's style attribute, and 2) it only works if it can work based on the markup and the current CSS. In your case, all the huffing and puffing and !important declarations won't make an image do something it can't do.
I answered a similar question in another SO page..
https://robau.wordpress.com/2012/04/20/override-image-src-in-css/
<img src="linkToImage.jpg" class="egg">
.egg {
width: 100%;
height: 0;
padding: 0 0 200px 0;
background-image: url(linkToImage.jpg);
background-size: cover;
}
So effectively hiding the image and padding down the background. Oh what a hack but if you want an with alt text and a background that can scale without using Javascript?
Use your 'userscript' to change 'src' attribute value.
If there is an ID there, you can do this:
document.getElementById('TheImgId').src = 'yournewimagesrc';
If there is no ID:
var imgElements = document.getElementsByTagName('img');
Do iteration of imgElements. When its src value is match with your criteria, change the value with your own, do break.
Update:
Javascript:
<script language="javascript">
function ChangeImageSrc(oldSrc, newSrc) {
var imgElements = document.getElementsByTagName('img');
for (i = 0; i < imgElements.length; i++){
if (imgElements[i].src == oldSrc){
imgElements[i].src = newSrc;
break;
}
}
}
</script>
HTML:
<img src="http://i.stack.imgur.com/eu757.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<img src="http://i.stack.imgur.com/IPB9t.png" />
<script language="javascript">
setTimeout("ChangeImageSrc('http://i.stack.imgur.com/eu757.png', 'http://i.stack.imgur.com/IPB9t.png')", 5000);
</script>
Preview:
The first image will be replaced after 5 secs. Try Live Demo.
you'll have to place the first image as a background-image too. Then you can override it. You could do in a "standard" css file for the site, and every user gets its own, where he can override what he wants.
i agree with all the answers here, just thought id point out that 'browsers' such as IE won't like the img[src="/img/test.gif"] as a means of selecting the image. it would need a class or id.
The images shown in tags are in the foreground of the element, not the background, so setting a background image in an won't override the image; it'll just appear behind the main image, as you're seeing.
What you want to do is replace the image. Here's your options:
Start with an element with a background image, not an tag. Then changing the background image in CSS will replace it.
Start with an tag, but use Javascript to change the src attribute. (this can't be done in CSS, but is simple enough in JS)
EDIT:
Seeing your edit in the question, I'd suggest option 2 - use Javascript to change the src attribute. It's quite simple; something like this would do the trick:
document.getElementById('myimgelement').src='/newgraphic.jpg';
You should be able to replace it by just doing something like:
.image {
content: url('https://picsum.photos/seed/picsum/400');
width: 200px;
height: 200px;
}
Unfortunately seems that it does not work in Firefox :(