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;
}
This is the output:
Here is another example:
h1{
color: red;
color: blueviolet;
}
h1{
color: orange;
}
and this is the output:
Specificity
This rule works on how specifically an element is selected.
Here is the order:
id
attribute
class
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>
The rule targeting the id
is applied, as it has the highest priority.
Type
There are 3 ways in which you can apply styles to your HTML.
Internal style sheet: This method uses an internal style sheet, which means that you specify style in your HTML within the
style
tags.External style sheet: In this approach, you link an external style sheet to your HTML using
<link rel="stylesheet" href="./style.css">
in thehead
element.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:
- Inline style.
- Internal style sheet
- 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;
}
Here is the output:
Top comments (0)