DEV Community

zaira
zaira

Posted on • Updated on

Cascading in CSS

In CSS, it is possible to apply multiple styles to a single element. However, there is an order or precedence. One style always takes precedence over the other.

In this article, we would learn how precedence works.

Position

The lower down a property is in the style sheet, the more important it is.

h1{
    color: red;
    color: blueviolet;
}
Enter fullscreen mode Exit fullscreen mode

This is the output:

applied blueviolet

Here is another example:

h1{
    color: red;
    color: blueviolet;
}

h1{
    color: orange;
}
Enter fullscreen mode Exit fullscreen mode

and this is the output:

applied orange

Specificity

This rule works on how specifically an element is selected.
Here is the order:

  1. id
  2. attribute
  3. class
  4. element

This means that an id selector would override an attribute selector and a class selector would override an element selector.

Let's see an example HTML, we would apply styles to the li:


<ul>
  <li id="all-items" class="list-items" draggable="true">First</li>
  <li id="all-items" class="list-items" draggable="true">Second</li>
  <li id="all-items" class="list-items" draggable="true">Third</li>
  <li id="all-items" class="list-items" draggable="true">Fourth</li>
  <li id="all-items" class="list-items" draggable="true">Fifth</li>

</ul>

Enter fullscreen mode Exit fullscreen mode

The rule targeting the id is applied, as it has the highest priority.

id rule applied

Type

There are 3 ways in which you can apply styles to your HTML.

  1. Internal style sheet: This method uses an internal style sheet, which means that you specify style in your HTML within the style tags.

  2. External style sheet: In this approach, you link an external style sheet to your HTML using <link rel="stylesheet" href="./style.css"> in the head element.

  3. Inline style: In this method, the style is applied using the style attribute inside an element. For example: <h1 style="color: aliceblue;"></h1>

The order of precedence of applying styles is as follows:

  1. Inline style.
  2. Internal style sheet
  3. External style sheet

Importance- adding the important keyword

If you specify that a property is important in your CSS, you can re-inforce that rule, regardless of the order.

li{
font-weight: 600;
color: rebeccapurple;
color: brown !important;
}

Enter fullscreen mode Exit fullscreen mode

Here is the output:

brown re-inforced

Top comments (0)