The given below are the order by which specificity of CSS is affected
Priority-1: !important keyword
Priority-2: Inline-style
Priority-3: Id selector
Priority-4: Class selector
Priority-5: Tag selector
Let understand how certain styles get applied based on priority as above with an example.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
/* Tag selector */
h1 {
color: blue;
}
/* Class selector */
.one {
color: crimson
}
.two {
color: green;
}
/* Id selector */
#id1 {
color: purple;
}
/* !important keyword */
h1 {
color: orange !important;
}
</style>
<body>
<div>
<h1 style="color:yellow;" class="two one" id="id1">Learn Code Online</h1>
</div>
</body>
</html>
Explanation:
In CSS, order of writing stylesheets matters a lot (may be inline or external style sheets)
Lets see what color our <h1>Tag
gets:
- If we write styling based on
h1
Tag Selector.
we get color ash1 { color: blue; }
blue for our
<h1>
Learn Code Online</h1>
- If we write styling based on
.one
Class Selector . (Overwrites Tag selector with class selector.one
).
we get color as.one { color: crimson }
crimson for our
<h1>
Learn Code Online</h1>
If we write styling based on .two
Class Selector. (Overwrites class selector .one
with class selector.two
).
.two {
color: green;
}
we get color as
green for our
<h1>
Learn Code Online</h1>
we can add more than one class or id to an HTML element. In that case, for above example we assigned two classes to our <h1>
tag
class="two one"
what color do you think you will get as output ???
The Answer is
green
because, our class.two
is below class.one
. Don't get confused by seeing class orderclass="two one"
mentioned as attribute in<h1>
Element. We can give class names in any order to a element. But where the order matters is inside<style>
tag or yourstylesheet
3 . If we write styling based on #id1
ID Selector. (Overwrites class selector with Id selector).
#id1 {
color: purple;
}
we get color as
purple for our
<h1>
Learn Code Online</h1>
.
4 . If we write styling on inlinestyle
attribute .(Overwrites Id selector with Inline styling ).
<h1 style="color:yellow;">Learn Code Online</h1>
we get color as
yellow for our
<h1>
Learn Code Online</h1>
.
5 . If we write styling with !important
keyword in our CSS next to value before " ;
" any selector{ property:"value"}
.It takes highest priority .(Overwrites Id selector with Inline styling ).
h1 {
color: orange !important;
}
we get color as
orange for our
<h1>
Learn Code Online</h1>
So our Entire example returns color > orange
That's the end of the topic ๐. Thanks for Reading! .Happy Coding! ๐คฉ