HTML:
<div id="test">This is a test</div>
JavaScript:
var elem = document.getElementById('test');
elem.style.setProperty('color', 'green', 'important');
elem.style.color = 'red';
Live demo: http://jsfiddle.net/4fn6h/3/
The text is green in Chrome, Safari, and IE9, but red in Firefox, and Opera. (Also, the text is black in IE7, and IE8, because the code throws an error, but let's ignore that... )
So, which browsers follow the standard here? Should it be possible to override a setProperty(...,'important')
or not?
important is if you have to override a style that cannot be overridden in any other way. This could be if you are working on a Content Management System (CMS) and cannot edit the CSS code. Then you can set some custom styles to override some of the CMS styles.
To override the CSS properties of a class using another class, we can use the ! important directive. In CSS, ! important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.
CSS makes the front-end of a website shine and it creates a great user experience. Without CSS, websites would be less pleasing to the eye and likely much harder to navigate. In addition to layout and format, CSS is responsible for font color and more.
The spec is not clear. There are two ways to look at it:
color
value, there is no reason for the old value to stay around, important or not.style
manipulates the style
property of the element, which is considered a CSS Declaration Block. In a CSS block, a property with !important
set will always take precedence over ones without. By that rule the change to 'red' should have no effect, so it's effectively ignored.I believe the latter is the most likely explanation. Consider having a declaration like this:
p { color: red !important; }
If you add a second color
rule, without !important
, it has no effect:
p {
color: red !important;
color: blue;
}
/* the color is still red */
The same applies to manipulating the HTML style
attribute directly.
So the behavior in Chrome/Safari/IE9 is consistent with the CSS cascading rules, while FF and Opera are treating DOM style as a simple object without regard for the cascading rules, not as an interface to the CSS declarations.
http://www.w3.org/TR/2000/REC-DOM-Level-2-Style-20001113/css.html#CSS-CSSStyleDeclaration
Fun fact: webkit seems to be doing a string match for important
, so this works too:
elem.style.setProperty('color', 'red', 'this is a really important rule');
And a tip: pick a better color pair next time, you're making it hard for the color blind to help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With