Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

CSS

CSS Specificity - Part 2

Notes:

CSS Specificity - Part 2 :
Specificity is the value calculated by examining the selector part of a CSS rule set, used to determine which selector is more specific than other selectors

Syntax of CSS rule set:
selector
{
declaration list;
}
If the calculated specificity of a selector gets more points, then that selector is considered as more specific, so remember more specific selector wins over less specific selector

!import (1,0,0,0,0)
Inline style (0,1,0,0,0)
ID selector (0,0,1,0,0)
Class selector, Attribute selector, Pseudo class (0,0,0,1,0)
Element selector, Pseudo element (0,0,0,0,1)

Two important points to remember:
1. Try to reduce specificity of a selector
2. Never use !important until and unless it is necessary

Example Code:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Specificity demo</title>
<style type="text/css">
p /* (0,0,0,0,1)*/
{
background-color:red !important; /*(1,0,0,0,0) */
}

p /* (0,0,0,0,1)*/
{
background-color:green;
}

body > p /* (0,0,0,0,2)*/
{
background-color:yellow;
}

.firstp /* (0,0,0,1,0)*/
{
background-color:cyan;
}

p.firstp /* (0,0,0,1,1)*/
{
background-color:magenta;
}

#first /* (0,0,1,0,0)*/
{
background-color:blue;
}

</style>
</head>
<body>
<!-- inline style (0,1,0,0,0) -->
<p class="firstp" id="first" style="background-color:green;">
Paragraph text
</p>
</body>
</html>

Interview Questions:

1. What is the specificity value of inline styles in CSS?
a. (1,0,0,0,0)
b. (0,0,0,1,0)
c. (0,0,1,0,0)
d. (0,1,0,0,0)
Answer: d

2. Calculate the specificity for following selector:
html > body > div#first > p.solidBorder
{

}
a. (0,0,1,2,2)
b. (0,1,0,1,4)
c. (0,0,1,1,4)
d. (0,1,1,1,0)
Answer: c