This is the 13th day of my participation in Gwen Challenge
First, what is priority:
That is, priority determines how to display these styles on the page. Priority is a matching rule based on different kinds of selectors. For more information about CSS selectors, see “Getting CSS Selectors Once and for all”.
How is the priority calculated?
Note: The proximity of elements in the document tree has no effect on priority
Let’s say we’re styling the same div in code like this.
<body>
<div id="box" class="container"></div>
</body>
Copy the code
Wildcards VS label selectors
When we declare both the wildcard and the label selector, the label selector has a higher priority than the wildcard, so it appears green in the box.
<style>
.container {
text-align: center;
color: white;
height: 200px;
width: 200px; {} *background-color: firebrick; /* Wildcard */
}
div {
background-color: green; /* Label selector */
}
</style>
Copy the code
Attribute selector VS tag selector
Again, let’s change the selector type.
div {
background-color: green; /* Label selector */
}
.container {
background-color: crimson; /* Property selector */
}
Copy the code
As you can see, the attribute selector has a higher priority than the label selector, so it’s red.
Id selector VS attribute selector
.container {
background-color: crimson; /* Property selector */
}
#box {
background-color: gold; /* id selector */
}
Copy the code
It follows that,The ID selector takes precedence over the attribute selectorSo it’s golden.
Inline style VS ID selector
We actually write inline styles in development, so we’ll see which takes precedence.
<div id="box" class="container" style="background-color: hotpink;"></div>
Copy the code
#box {
background-color: gold; /* id selector */
}
Copy the code
Display effect 👇
So inline styles actually take precedence over regular selectors.
! important
In addition,! Important is the exception when used in a style! The important rule overrides anything else.
For example, if we just set the background color in the wildcard with the lowest priority, the other selector styles remain unchanged.
* {
background-color: indigo ! important;
}
/* Label selector */
div {
background-color: green;
}
/* Property selector */
.container {
background-color: crimson;
}
/* id selector */
#box {
background-color: gold;
}
Copy the code
See, use! Important has the highest priority, so overrides the previous styles.
But blind use! Important is a bad habit because it breaks the rules in the stylesheet and makes it very difficult to debug.
To summarize the priorities on the selector:
! Important > Inline Style > ID selector > Class selector/property selector > Tag selector > Wildcard *