Selectors and specificity
Basics Of CSS Part-2
Coding fun
Welcome to the part two If you haven’t read part one here is the link.
In first part we have covered how we can include CSS in our project.Now lets start with Selectors and specificity.
Selector
CSS selectors define the elements to which a set of rules apply.
We have couple of selectors available as follow
- Universal Selector
- Class Selector
- Type Selector
- ID Selector
- Attribute Selector
Lets see example of each selector
- Universal Selector selects all the elements. Some times you want to set certain style to all the element on the entire page in this case we can use universal selector
2. Class Selector selects all the elements that have the given class attribute.We can give any name that we want to the class.Style will be applied to all the element which have the class name.
3. Type Selector selects all elements that have given node name.The type selector matches element by node name i.e. It selects all elements of given type within the document.
4.ID Selector Selects an element based on the value of its id attribute.There should be only one element with given id in the document
5. Attribute Selector selects all elements that have the given attribute.Using attribute selector we can select multiple elements unlike id selector which only selects one element
Specificity
To understand specificity lets first understand what cascading means in CSS.
Cascading means applying multiple styles or rules to the same element .Now these rules may lead to conflicts. see below example
CSS executes in top to bottom manner and in the CSS code we have applied white color to the h1 tag but in output h1 tag has blue color as we are applying multiple rule to same element using different selectors so we are not getting expected output that is h1 text in white color .
Now to resolve such conflicts CSS knows a concept called specificity.
There are clear rules included in CSS specifications that defines how such a conflicts should be resolved. To know which type of selector have higher specificity and which type of selectors have lower specificity refer below diagram and for more information visit this link
Specificity is the means by which browser decides which CSS values are the most relevant to an element , therefore , will be applied. Specificity is based on different matching rules composed of different CSS selectors.
That’s for now I hope you liked the post if yes don’t forget to clap. It will motivate me thank you :)