[CSS] The Cascade and Specificity

Have you ever been wondering that what is CSS? Literally CSS is Cascading Style Sheet, so then what is the Cascading? I will introduce you guys to basic CSS meaning and priorities.

 

Before we start the main context, you should know the right terms of CSS.

1. Cascade.

Cascade: Process of combining different stylesheets and resolving conflicts between different CSS rules and declarations, when more than one rule applies to a certain element.

 

Yes, this is definition of Cascade in CSS. Might you know that even a simple web application has several css files and which on should be applied first? In this post you will learned which one has the highest priority and you can use it intentionally.

 

2. Priorities.

  1. IMPORTANCE
    1) User: important declarations
    e.g. background-color: blue !important;
    2) Author: important declarations
    3) Author declarations
    4) User declarations
    5) Default browser declarations
  2. SPECIFICITY
    1) Inline styles
    2) IDs
    3) Classes, pseudo-classes, attribute
    4) Elements, pseudo-classes-elements
    e.g.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    .button {
        font-size: 20px;
        color: white;
        background-color: blue;
    }
     
    nav#nav div.pull-right .button {
        background-color: green;
    }
     
    {
        background-color: purple;
    }
     
    #nav a.button:hover {
        background-color: yellow;
    }
    cs

    .button (inline: 0, IDs: 0, Classes: 1, Elements: 0) 
    nav#nav div.pull-right .button (0, 1, 2, 2)
    a (0, 0, 0, 1)
    #nav a.button:hover (0, 1, 2, 1)
    You should calculate it first one which is inline. Every inlines are 0 so pass to the second one. IDs column, second and fourth selectors have value 1 so move to the third column. on the Elements column, second selector has 2 elements so second selectors declarations are applied into the file.

  3. SOURCE ORDER
    The last declaration in the code will override all other declarations and will be applied

3. Other Rules!

  1. CSS declarations marked with ! important  have the highest priority
  2. But only use ! important as a last resource. It's better to use correct specificities - more maintainable code
  3. Inline style will always have priority over style in external sheets;
  4. A selector that contain 1 ID is more specific than one with 1000 classes
  5. A selector that contain 1 Class is more specific than one with 1000 elements
  6. The universal selector * has no specificity value (0,0,0,0)
  7. Rely more one Specificity than on the order of selectors. 

 

 

Leave a Comment

ko_KRKorean