CSS Selector Specificity

A lifelong learner. Love to travel. Listen to music.
Search for a command to run...

A lifelong learner. Love to travel. Listen to music.
No comments yet. Be the first to comment.
Best Practices for Path Structure, Versioning, and Error Handling

Understanding the Performance Implications of async and defer Attributes

Overview static: Default position. It does not allow setting properties like top, bottom, left, right, z-index relative: Acts the same as static. but allows positioning it relatively by putting properties like top, bottom, left, right, z-index absolu...

Master block, inline, flex, and grid to build better web layouts

When an element in the browser has a conflict of styles, the browser uses a set of rules to determine which style should be rendered. This set of rules is defined as CSS Selector Specificity.
For instance, for an element, if we have the following DOM and CSS classes,
.myClass {
color: yellow;
}
<div style="color: red;" class="myClass">My Text</div>
In this case, the color will be red, since the inline style has higher weight.
The browser uses an array of four elements, where the previous index has higher priority. Consider these four elements a a, b, c and d.
[a, b, c, d]
A = Inline styles
B = Number of selector IDs
C = Classes, Pseudo Classes, and Attributes
D = Elements and Pseudo-Elements
We calculate A, B, C, D as follows,
body.home #sidebar .menu li a:hover {
color: gold;
}
Let’s break it down:
body → element → +1 to d
.home → class → +1 to c
#sidebar → ID → +1 to b
.menu → class → +1 to c
li → element → +1 to d
a → element → +1 to d
:hover → pseudo-class → +1 to c
Specificity: 0,1,3,3
Higher specificity wins.
If specificity is the same, the last declared rule in the CSS wins.
Inline styles have the highest specificity (except !important).
!important can override normal specificity but should be used sparingly.
Write CSS with low specificity, so we can override it later
Avoid nested selectors and keep them shallow