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 the selectors:
This is one of the most important parts of CSS and it explains what you are observing.
The different types of selectors have different precedence.
The order is:
!important >> style="attr: valor" >> #id >> .clase >> div
Detailed:
The use of !important
: any rule with !important
wins over all others and always applies, unless two rules include !important
in which case, the other rules apply to determine what the value of the attribute.
Attribute style
of the element, or <div style="color: red;">
, what you specify here takes precedence over any other style in a file .css
, except for one with !important
(this applies to all other cases).
Styles set by #id
: Styles such as #id { color: blue; }
are the most important within .css
.
Styles set by .clase
: styles as .clase { color: white; }
the workhorse of .css
, since they are in the middle of the spectrum and can easily be overwritten by #id
or as we will see later by amount of coincidences
Finally, div
or element: setting attributes by div { color: yellow; }
is the least precedent and is usually used to set default values.
Example:
#id { background: yellow; }
.rojo { background: blue; }
div { background: red; }
.mata_a_todos { background: orange !important; }
<div id="id" class="rojo mata_a_todos" style="background: green;">hola</div>
<div id="id" class="rojo" style="background: green;">hola</div>
<div id="id" class="rojo">hola</div>
<div class="rojo">hola</div>
<div>hola</div>
The number of matches
Consider that you have a div
with a class and 3 rules:
div { background: black; }
div.rojo { background: red; }
.rojo { background: blue; }
<div class="rojo">hola</div>
Here the second rule takes precedence because it has more matches than any of the other two. Notice that the order in which the rules appear in the CSS does not matter.
These are the basic rules of CSS precedence.
At the request of @ AlvaroMontoro, these rules are known as CSS Specificity.