I know it's possible to specify multiple classes on an element in HTML:
<div class='one two'>Text</div>
It seems like classes are accessible from Javascript as a single string.
What happens when the classes are specified with conflicting properties? For instance
div.one { background-color: red; color: blue; } div.two { background-color: green; }
Will the result depend on the order the classes are specified in? For instance could I reasonably expect the div above to appear with blue text and a green background, because the two
class becomes evaluated second, overwriting the background-color
property?
To resolve such conflicts, you have CSS Cascade. The CSS Cascade is a way for browsers to resolve conflicting CSS declarations. By specifying CSS rules, you specify where the CSS style is added to the cascade hierarchy. The further down a hierarchy a declaration falls, the less likely it will end up as the final style.
If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element. Think of specificity as a score/rank that determines which style declaration are ultimately applied to an element.
You need to keep the widget CSS rules as self-contained as possible, which means that you will need to specify every property that is critical to you design, and make sure that properties like float: none , position: static and so on are explicitly set.
Read about specificity:
Short answer: if two selectors have the same specificity, the last one to be declared wins.
CSS has a very well defined order of precedence.
In instances like this, where all else is the same and the precedence is equal, the browser should pick the style defined last in the stylesheets.
In the example you've given, this would mean that the div.two
styles would override div.one
, where the same property is defined in both.
By the way, this is also the same feature that allows you to do define multiple styles with the same property in the same selector, to support different browser features. For example, some browsers may not support rgba colours, so you can do the following:
.myclass { background: rgb(200, 54, 54); background: rgba(200, 54, 54, 0.5); }
All browsers will pick the last background
declaration that they support, so browsers which support rgba
will pick the second one, while browsers that don't, will make do with the first one.
It is also the reason why, when you use vendor prefixed styles, you should also specify the non-prefixed version after the prefixed version(s), so that when that vendor's browser does start supporting the non-prefixed version of the style, you can be sure it'll use it rather than the prefixed version (which may not support all the features of the final version).
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