Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 9, 2022 11:22 am GMT

CSS Specificity

As a Frontend Developer, you might have came across the situation, where your CSS isn't working as expected or not getting applied where it should be. And then you end up wasting your time writing wrong CSS or refactoring all styles here and there.

ugh-meme

Ugh!!
Here CSS Specificity comes into picture. And why you should know it as a frontend developer.

What is CSS Specificity?

What internet says,

CSS Specificity is the set of rules applied to the CSS selectors to determine which style will be applied to an element.

We know CSS stands for Cascading Style Sheet, and cascading means the sequence of order in which CSS rules will be applied.

Before going ahead, let' revise CSS Selectors.

CSS Selectors

  • Universal Selector ( * )
* {    background-color: red;  }

Universal Selector's style will apply throughout the webpage but it has no specificity. That means any other style with more points will take over it.

  • Inline Styles
<div style="color: red;">Hello World!</h1>

Inline style has highest priority. Which will override other style.

  • IDs ( # )
<div id="my-heading">Hello World</h1>
#my-heading {  color: blue;}

ID have second highest priority.

  • Classes, pseudo-classes and attributes
.my-heading {  color: blue;}

Classes, pseudo-classes and attributes will have less priority as compare to IDs.

  • Elements and Pseudo Elements
div {  color: gray;}//pseudo element::selection {  color: yellow;}

Elements and Pseudo elements has lowest priority.

  • !important
.my-heading {  color: pink !important;}

An !important has the highest specificity and will take over all the other CSS properties.
When we use !important, no other style like inline style, ID, class will work.

specificity-

Let's see some example,

Example 1

ul > li {  color: red;}

Specificity: 0 - 0 - 0 - 2

list > list-items {  color: blue;}

Specificity: 0 - 0 - 2 - 0

So, the second will override the first as it has the high specificity.

Example 2

  a.my-class.another[href]:hover {    //some properties  }

Specificity: 0 - 0 - 4 - 1

Visualizing Specificity

For inline styling, the specificity will be

inline-visual

For IDs styling, the specificity will be

id-visual

For Classes, pseudo-classes and attributes styling, the specificity will be

classes-visual

For Elements and pseudo elements styling, the specificity will be

pseudo-element-visual

Hope now have understood the CSS Specificity.

Resources

Specificity

CSS Selectors


Original Link: https://dev.to/shraddhaaa7/css-specificity-4cna

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To