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 use the react-slick library to make a slider. I have images inside the tag responsible for the slider. Depending on the size of the screen I would like to hide the images but the property slick.css blocks my css style. How could I turn it off?
You can try to write a more specific css selector.
I assume your image has a class .cHgPZg.
If yes you can try the selector
.slick-slide img.cHgPZg { dsiplay: none; }
If this is not working you can always use the !important; but try to avoid it if possible.
.cHgPZg {display: none !important;} // not recomanded
The issue is specificity. You have to add a more specific selector in order to overwrite the dominating selector and hide the image. Try walking the selector tree backwards until the selector is specific enough; Something like this:
.slick-slider .slick-list .slick-slide img {
display: none;
}
I am using HTML to input a cloud-based instagram feed on a website. I want to hide the bottom half of the feed that references the website of the publisher. The inline HTML that is outputting already has display: inline-block !important marked, so trying to hide it with display: none !important or visibility: hidden !important do not work. I am able to hide the entire block with CSS but not "parts" of it. I don't seem to be able to edit the HTML since it is coming from the cloud. The only HTML that I actually use on the site in order to make it render does not include any of the inline CSS, as it is only two lines.
Would someone mind explaining how this kind of thing works and why I am encountering issues overriding the inline CSS?
I have tried using:
display: inline !important, display: none !important and visibility: hidden !important
None of these are receiving priority, as the element.style in the chrome developer console clearly shows the inline CSS already marked as !important that I do not have access to, nor can I edit.
I simply want to hide one selector within the HTML. It is marked as "a"
a {
}
I have tried using this selector within the actual element, but it does not receive priority either. Nothing is working.
Try to remove the inline style with jQuery
$("#myDiv2").css("transform","");//used rotate to see the effect
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="myDiv1" style="width:100px !important; height:100px !important;transform:rotate(30deg) !important">
//Some Content
</div>
<div id="myDiv2" style="width:100px !important; height:100px !important; transform:rotate(30deg) !important">
//Some Content
</div>
Setting the value of a style property to an empty string removes that property from an element.
$("#myDiv2").css("transform","");
Typically the only way to do this is to be more specific in your selector, for example selecting a[href][style] is more specific than just a. But since this is inline styles and already using !important you unfortunately might be out of luck!
a[href][style]{
color: green !important;
}
This link uses !important
<br/>
This link does not
If you wanted to just remove the links without importing several thousand lines of jQuery code, you can select and remove all <a> tags with just a few lines of plain JS.
document.querySelectorAll('a').forEach(link => {
link.remove();
});
<p> here is some text
This link uses !important
<br/>
This link does not
and some more text
</p>
I have a CSS conflict going on with a major plugin in my wordpress site. The plugin maker found it handy to add !important declarations throughout all their styling sheets. From a developer's perspective; this is a disaster. In their defense they want to cover all themes that are using !important declarations, so it looks consistent. I do not agree, so I need a solution.
What happens is that my premium theme, who's not using those declarations, cannot override the styling. I have some solutions to remove certain classes by jQuery.
But there is a problem which cannot be resolved by removing classes. For example, the anchor:hover is default as border: none !important by the plugin. But I would like to see is that the anchor:hover border option is actually applied via the theme settings. The applied CSS is this (be aware that the .plugin class is not applied in the anchor, just from a CSS file):
.plugin a { border: none !important; }
Is there any way I can disable certain class combinations from the DOM? I'm happy to have this done with php or jQuery. Something like: .plugin is not applied to anchor I have no idea how to resolve this.
Surely this is just a case of overwriting the css with a better specified css line.
For example if the code is:
.plugin a::hover { border: none !important; }
You can overwrite this by doing:
body .plugin a::hover { border: 1px solid grey !important; }
Because you have added the element body to your css line it adds extra specificity meaning it overwrites the plugins css. You unfortunately have to use !important, as !important throws regular specificity ruling out the window (bad plugin creator).
More on css specificity here
Do you need any of the styles provided by the plugin? If not then it might be worth looking at dequeueing the plugin styles altogether and just adding your own styles where the theme doesn't cover it.
If you find out the registered name of the stylesheet (should be in the style tag) you can dequeue it with something like:
function remove_push_plugin_styles() {
wp_dequeue_style( 'plugin-stylesheet' );
}
add_action( 'wp_print_styles', 'remove_pushy_plugin_styles', 1000 );
You aren't able to edit an iframe's content, true. But the iframe's itself still belongs to your page, and you can edit the attributes. I just tested and was able to do something similar to:
var i = $('div.item iframe');
// Did the selector work?
console.log(i.length);
i.removeAttr('width');
i.removeAttr('height');
That being said, using !important in this situation is not bad. If you're worried about CSS maintenance, leave a comment that the !important is overriding the element's attributes. !important is often demonized, but in this case it is a valid use to increase the specificity of your CSS.
The advantage of doing it in CSS is that it will apply before your JavaScript is loaded, so you won't get a split second of those attributes and styles applying before the JavaScript removes the styles.
I am doing a code that do some js injection of code in page, with JQuery. But in my input that i get in some pages modify it, I am putting all important attributes and define them as !important, but it's impossible to put all the attributes in all the tags.
Someone know how to disable all other css inside a div?
Solution I think:
I found a solution but i don't want to use it. Its eliminate al css from the page, while i am injecting the code after using that code I eliminate my css and code and apply the original code from the webpage
Thanks
If you're using that many !importants you're doing it wrong.
The solution to this problem is to properly organize your css. Important stuff last, because it overrides what was previously styled. Also use your selectors wisely. Example:
<a class="link">Link</a>
.
a:link { color: red; }
.
.
.
.link { color: green !important; } // Nop
a.link { color: green; } // Yup
If you override everything it will work with normal CSS rules on every page. Not what you were hoping for, but it is a solution.
css:
#myInsertDiv {
color: blue;
padding: 0;
margin: 0;
background: white;
border: 0px;
/* etc you have to restyle EVERY possible value */
}
html:
<div id="myInsertDiv"></div>
The main issue is you have to style every attribute, and reset everything else to a default value.
Or you can insert all the style information into the style attribute on the div, but that is probably doing it wrong too.
If I got you right you can use jQuery for modifying CSS properties on any elements of the page (huh), using something like this $('.Myclass').css('color','#ff0000')
And more about selectors in jQuery - http://api.jquery.com/category/selectors/