Properties defined in, #id vs .class


I have a question about the use of div and .class .

I have an HTML5 document with several div . The point is that the div has defined CSS properties and I intend to modify them using a class. When I try it, I check that when I define a value for a property in the class, if that 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 would like to know why this happens and if it happens, or not, with all the properties that you use. And finally, what about the compatibility between #id and div , and between div and .class .

asked by Hugo Sanchez 04.05.2016 в 13:35

1 answer


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


  • 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>

    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.

    answered by 04.05.2016 / 14:51