So I've already got the text color of a select box set with an !important value and am struggling to change it again using jQuery.
<div class="halio-form-container">
...
<select class="form-control" id="HalioDirection" name="halio_direction">
<option selected="" disabled="">Direction...</option>
<option value="one_way">One Way</option>
<option value="return">Return</option>
</select>
...
</div>
.halio-form-container select {
color: #B0A9A9 !important;
}
Any thoughts?
The best solution is to not use the !important at all and refactor your css (and possibly markup) such that proper selector specificity allows you to do what you need without !important.
That being said, general way to override an !important is to add another CSS rule with !important with either a higher specificity, or same specificity but defined at a later point. This works because in a specificity tie, the last rule defined wins.
Related question: How to override !important
Since we need to use JS/jQuery and not CSS, there are three possible solutions:
1. Add an inline !important rule
We can beat !important with a more-specific rule by adding an inline !important rule.
The reason this works is because inline styles always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
var currentStyle = $('#test').attr('style') || '';
$('#test').attr('style', currentStyle + ' color:red !important');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
2. Add a new style element
We can beat !important with a later-defined-equally-specific !important rule by creating another stylesheet containing this rule and appending it to <head>.
$('<style>#test { color:red !important; }</style>').appendTo('head');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
3. Append to last style element
Basically another version of 2. where, instead of creating a new style, we append our new rule to the end of the last style:
var lastStyle = $('style').last();
lastStyle.html(lastStyle.html() + '\n#test { color:red !important; }');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
Additional resources:
MDN
Related
I'm rendering dynamic CSS for each item in a list. Each item will have potentially unique CSS rules for its elements, i.e.
<div id="thing1" class="vegas">
<style>
p {
font-size: 14pt; // this stuff is generated dynamically and i have no control over it
color: green;
}
</style>
<p>
I'm thing 1!
</p>
</div>
<div id="thing2" class="vegas" >
<style>
p {
font-size: 9pt; // so is this stuff
color: red;
}
</style>
<p>
I'm thing 2!
</p>
</div>
Is there a way to wrap each item in a general CSS rule that would limit the scope of each item's associated CSS to the item itself? Like
.vegas > * {
whatever-happens-in-here: stays in here;
}
Or any other way to handle scoping who-knows-what kinds of dynamically particular CSS?
The cascading style sheets are able to handle styling children of particular elements, so:
div#thing1 p {
rule: value; // Only applies to p in div with id="thing1"
}
div#thing2 p {
rule: value; // Only applies to p in div with id="thing2"
}
You need to know about the global styles that browsers have. For eg., find the below list:
font-family
line-height
text-align
The above have their default value as inherit, which means they get the property values from their parent, no matter what. So if you change the parent's property, your child also gets changed.
And you have other properties like:
margin
padding
border
width
height
These do not change, or inherit from the parent. So, if you wanna do something like what you wanted, you need to give your descendants, or immediate children, not to inherit or reset the styles for the children.
Why don't you use inline style attribute?
<p style="color:red;align:center"> Hello </p>
The above CSS style will only be applied to that particular paragraph tag.
You could use inline style statement for other tags and HTML elements too.
Or you could include an external common stylesheet and use the inline statements where you need a variation.CSS applies the latest style description it comes across.So the inline statements would over-ride the common css stylesheet effects.
I'm trying to get the real style of an inline element but it's always getting the css applied to it. I don't want to modify my CSS, too many pages depend on it.
<body class="processed" style="padding-top: 157px ;margin-top: 0px;">
My CSS
.processed{padding-top: 56px !important;}
JS:
$(function(){
var pad = $('body').css('padding-top');
$('body').attr('style','padding-top:'+ pad +' !important; margin-top: 0px;');
console.log('pad' + pad);
});
The result: body with inline style 56px, instead of 157px...
You could create a second "important" class in the CSS file, so it wouldn't affect those other pages, but it would override that first "important" class.
You just have to write that new class after the first one.
For example:
HTML:
<body class="processed processed-large-top">
CSS:
.processed{padding-top: 56px !important;}
.processed-large-top{padding-top: 157px !important; margin-top: 0px;}
Solved, the problem was an script overriding styles after DOM ready...the !important played a good role..
A CSS rule with !important have higher priority than inline styles. To override it, you have to use !important also on the inline style CSS.
So, your HTML tag have to end up like this:
<body class="processed" style="padding-top: 157px !important;margin-top: 0px;">
<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
background-color:red;
}
.green {
background-color:green;
}
</style>
</head>
<body>
<div id="sample" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').addClass("green");
}, 2000);
</script>
<html>
I want to change the background color of the div with id="sample" from red to green in 2 seconds.I added the javasript to add a class with a green background to the div after 2 seconds.But the added class fails to replace the background color of the div element.So is there any solution which can be applied here to change the background color in two seconds.Also i know it is possible,if we add an another class to toggle between the background colors.An another solution will be appreciated.
It's fails because the weight of ID more than the weight of CLASS:
id = 100
class, pseudo-class = 10
element, pseudo-element = 1
You can use id with class:
<body>
<div id="sample" class="red"></div>
</body>
And then toggle from red to green. No need to use !important.
Moreover, if you want to change it with animation, you can use jQuery animate backgroundColor
<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
/*Remove this from here*/
/*background-color:red;*/
}
.green{
background-color:green;
}
.red{
/*Create a class for red alone*/
background-color:red;
}
</style>
</head>
<body>
<div id="sample" class="red" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
// Calling removeClass with no parameters will remove all of the items's classes.
$('#sample').removeClass();
// Now add the class of green
$('#sample').addClass("green");
}, 2000);
</script>
<html>
Cause
The problem is that an id-style is more important (has more 'weight') than a class style, so #sample has higher precedence than .green and the div remains red. There are many rules that dictate which CSS rules have precedence over others. Make sure to read about CSS rule Precedence, so whichever solution you choose, you know why you chose it and what are the consequences.
Fix
There are many ways to fix this, but they all boil down to making sure that the green rule overrules (is equally or more important than) the default red rule.
Solution (Best): Style on classes, not on IDs.
Add a class to the div that indicates what kind of box it is:
<div id="sample" class="samplecontainer"></div>
Now, in the CSS you can easily apply a default style to such elements, and overrule them too:
.samplecontainer {
background-color: red;
}
.samplecontainer.valid,
/* Or just */
.valid
{
background-color: green;
}
Now the CSS doesn't rely on specific elements, but on element definitions. You can say that containers are by default red, and are made green when they become 'valid' (whatever that may mean in this example). This way, you don't rely on ids in the CSS, which prevents very bulky CSS and the undesirable overrule you bumped into.
Note I renamed 'green' to 'valid' to make it more semantic. What if you want to change the border too, or make them blue instead of green? Then you would still need to dig into the JavaScript code, and also change the class names in CSS and possibly fixed style names in HTML and PHP. Or you can just leave the class name 'green' for the blue element, which is very confusing too. So a name describing the type or state (like valid, active, or whatever suits you best) is easier to read and to maintain.
Solution (Sub-optimal): Add Id to the green rule too
Try do change the css like this, so indicate that an element that has id 'sample' and class 'valid' should be green. I think this is quick fix and less optimal compared to the previous one, and your CSS may become bulky if you have many elements that can become green.
#sample.valid{
background-color: green;
}
Solution (Poor): Adding inline style though JavaScript
Instead of adding a class through JavaScript, you can also add inline style. Inline styles (the style attribute), has higher precedence, so adding style="background-color: green" will overrule the color defined in CSS.
$('#sample').css('background-color', 'green');
I wouldn't much prefer this method, since you would have to dig in your JavaScript to change the styling, end it will get really clunkcy when you want to change other properties as well. Each of the solutions above are preferable over this one.
Solution (Poor and risky): Add !important
From CSSTricks: When Using !important is The Right Choice
The unfortunate typical use case goes like this:
WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG
(use !important rule)
OK, now it's working
Then the next guy comes along and tries to
make new changes. He tries to alter some existing CSS rules, but now
his changes aren't behaving how they should....
There are some cases when !important might be the right choice, but it should never be the quick fix for a problem like this, because in the end you'll and up with a CSS that is very hard to maintain, and various !importants will bite each other. Only use it when you have really thought it through.
Change CSS to
.green{
background-color:green !important;
}
DEMO
Please try this one and remove #simple style css
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').css({'background-color':'green'});
}, 2000);
</script>
in the JavaScript you can use just like that
you may find demo
var a;
function function_name() {
a = 1;
setInterval(new_function, 1000);
}
function new_function() {
if (a === 1) {
color = "requred_color";
a = 2;
} else {
color = "another_color";
a = 1;
}
document.body.style.background = color;
}
.green{
background-color:green !important;
}
change your green class like following
.green{
background-color:green !important;
}
Or try
$('#sample').css({background-color:"green"});
I am trying to make a jQuery plug-in that injects CSS rules onto the page. I am using addRule and insertRule. For some reason, addRule strips out !important from any rules you pass to it. Is there a way I can prevent it from doing so or a flag I can send to the function to mark the rule as important? I looked at the documentation for addRule but there was no mention of !important declarations.
document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));
var sheet = document.styleSheets[document.styleSheets.length-1];
sheet.addRule('body','color: green !important');
h1 {
color: yellow;
}
<h1>Test text</h1>
By the way, I am only using addRule for compatability with older versions of Internet Explorer. I am aware that insertRule is a more robust function.
I don't believe !important bubbles like you're expecting. !important lets rules take precedence over other rules with the same selector. Consider this example:
<style>
#me { color:blue !important; }
</style>
<p id='me'>Hello, World</p>
<script>
sheet.addRule('#me','color: green !important;');
</script>
You'll notice that #me should be blue by the stylesheet, but it's being overriden by the addRule.
In your example, you're saying you want body color to percolate down to paragraphs, but !important is about choosing between rules with the same selector, not hierarchy. CSS Tricks has some words on this.
I'd like to apply a CSS to some linkbuttons on page load but one of them <a id="lb1">logoff</a> must keep its style, no hover nor other event must change its style.
The linkbuttons have no class and the css applied to all of them is done to tags, this way:
a
{
//style
}
a:hover
{
// style
}
Is it possible?
No, you can't.
You can use more specific selectors (or even inline CSS with the style attribute) so that they are less likely to be overridden accidentally.
You can use the (eugh) sledgehammer of !important so they will only be overridden by another !important rule.
There is no way to prevent them being overridden though.
Please please please please please avoid using !important whenever possible. You will run into SO many annoying problems and issues from using this. I consider it a very lazy hack.
What you want to do is append a class to the link that you don't want overwritten. Classes are given a higher priority than general selectors (such a, p, b). So if you append this class to the link, the CSS will override the default CSS you have set for a.
CSS:
a {
color: red;
}
a:hover {
color: blue;
}
.derp:hover { /*you can add everything you want to preserve here, essentially make it the same as the link css. you can also change it to #lbl:hover, although there's no good reason to be using an ID as a CSS selector*/
color: red;
}
HTML:
this will turn blue on hover
<a class="derp" href="#">this will stay red on hover</a>
Here's a fiddle to show you. The second link has a class appended that preserves the original style: http://jsfiddle.net/p6QWq/
Why not add a class to all the link buttons you want to change, and not add it to the one you don't want to change.
Then you can call:
$(".myClass").css("backgound-color", "blue");
This would change the background color for every element with a class of myClass to a blue background.
Or you could add a whole new class to the link buttons that have a class of myClass:
$(".myClass").addClass("myExtraClass");
This would then make the class attribute of your link button class="myclass myExtraClass"
Seeing your code posted makes it a little more clear on what you want to do. Try this:
a {
text-decoration: none;
color: orange;
}
a:hover {
text-decoration: underline;
color: blue;
}
This would apply a default style to all <a> elements. Now you could overwrite this default style by providing a specific style for the anchor with the id you gave above:
#lb1 {
color: black;
text-decoration: none;
}
#lb1:hover {
color: black;
text-decoration: none;
}
I mocked this up in a quick and dirty jsFiddle. See if this gives you the desired result. IDs take precedence over classes and default element styling. So if you have one that you want to keep the same, apply and ID and style the particular element accordingly. This would also help you by preventing you from having to apply a class to several elements. It's less coding to apply one ID than to apply twelve classes. (Just an exaggerated example. I don't know how many links you have.)
Hope this helps.
css is cascading by definition, so any style you apply to a tags will apply to this specific one, except if you overwrite it.
You'll have to either assign a class to all the other buttons or overwrite all the default properties for this specific button.
Also, do not forget the pseudo-classes :visited and :active.
You should use !important in your css like :
a {
/* style */
background: #FFF !important;
}
a:hover {
/* style */
background: #FFF !important;
}
You could always overwrite your css by simply creating another stylesheet and place it at the END of your stylesheet links in the head of your html.
<head>
<link rel="stylesheet" href="location/location/first_stylesheet.css">
<link rel="stylesheet" href="location/location/revised_stylesheet.css">
</head>
This is not the most productive method of overwriting your css however; one would be well advised to eliminate the necessity for this separate stylesheet by simply appending elements with a class attribute. The class attr will allow you to modify basic html elements, tags and overlay a final layer to "rule them all". Enjoy!