I have a doubt in the use of div
and .class
.
I have an HTML5 document with several div
. The point is that it div
has defined CSS properties and I intend to modify them through a class. When trying, I verify that when I define a value for a property in the class, if that same property is previously defined in the div
, the value does not change unless the property defined in the class is accompanied by the hack !important
.
I'd like to know why this happens and whether or not it happens with all the properties I use. And finally, what about the compatibility between #id
and div
, and between div
and .class
.
To determine the value of the attribute, the browser needs rules. It is the precedence of one rule over another.
There are 2 main factors...
The order of precedence of selectors:
This is one of the most important parts of CSS and it explains what you are looking at. Different types of selectors have different precedence.
The order is:
Detailed:
!important
: any rule with!important
wins over all others and always applies, unless two rules include!important
in which case the other rules are applied to determine what the value of the attribute is.style
, or<div style="color: red;">
, which you specify here takes precedence over any other style in a file.css
, except for one with!important
(this applies to all other cases).#id
: the styles as#id { color: blue; }
are the most important within a.css
..clase
: styles like.clase { color: white; }
the workhorse of.css
, as they are in the middle of the spectrum and can be easily overwritten by#id
or as we will see later by number of matches.div
or element: setting attributes viadiv { color: yellow; }
is the least precedent and is often used to set default values.Example:
The number of matches
Consider that you have a
div
with a class and 3 rules:Here the second rule takes precedence as it has more matches than either of the other two. Note that the order in which the rules appear in the CSS does not matter.
These are the basic CSS precedence rules.
At the request of @AlvaroMontoro, these rules are known as CSS Specificity.