CSS

Last Updated: 10/5/2022

CSS Specificity

  • Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element
  • If there are two or more CSS rules that point to the same element, the selector with the highest specificity value will "win", and its style declaration will be applied to that HTML element.
  • Specificity is basically a measure of how specific a selector's selection will be

Specificity Hierarchy

  • Every CSS selector has its place in the specificity hierarchy.
	(x, y, z)
	x - no of of id selectors - add value of 100
	y - no of class selectors - add value of 10
	z - no of element selectors - add value of 1
  • Score (From highest to lowest)
    • ID selector - (1-0-0) - value of 100 - Highest
    • Classes, pseudo-classes, attribute selectors - (0-1-0) - value of 10
    • Elements and pseudo elements selectors- (0-0-1) - value of 1
    • * Universal selector - (0-0-0) - lowest - value of 0
/*Specificity (0, 0, 1) value = 1 */
h1 {
	color: red;
}
/*Specificity (0, 1, 0) value = 10 */
.heading {
	color: blue
}
/*Specificity (1, 0, 0) value = 10 */
#title {
	color: green
}
/*Specificity (1, 0, 1) value = 101 */
h1#title {
	color: yellow
}
<h1 class="heading" id="title">Selector Specificity</h1>

Order

  • When two rules have equal specificity, the one that is defined last will be used.
h1 {
	color: red;
}
h1 {
	color: blue;
}

Inline Styles

  • Inline styles, that is, the style declaration inside a style attribute, take precedence over all normal styles, no matter the specificity.
  • Such declarations don't have selectors,
  • Their specificity can be construed as 1-0-0-0;

Important Rule !important

  • Used to add more importance to a property/value than normal.
  • It will override ALL previous styling rules for that specific property on that element.
  • The only way to override an !important rule is to include another !important rule on a declaration with the same (or higher) specificity in the source code
  • Using the important keyword is considered a bad practice
h1 {
	color: red !important;
}
.heading {
	color: blue
}