Specificity and Order Assessments
Description
What if there are two styles applied to an element defined at the same level and they both contain values for the CSS property the browser is looking for.
To decide which value to use, the browser assesses the specificity of each style and selects the one that is most specific.
The browser determines the specificity of a style by counting three different characteristics:
- The number of id values in the style's selector
- The number of other attributes and pseudo-classes in the selector
- The number of element names and pseudo-elements in the selector
The browser combines the values from each assessment and applies the property value from the most specific style.
Example
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
a {<!--from ww w.ja va 2 s . c o m-->
color: black;
}
a.myclass {
color:white;
background:grey;
}
</style>
</head>
<body>
<a href="http://java2s.com">Visit the website</a>
<p>The is a test.</p>
<a class="myclass" href="http://w3c.org">Visit the W3C website</a>
</body>
</html>
When assessing specificity, you create a number in the form of a-b-c, where each letter is the total from one of the three characteristics.
Only if the a
values are equal does the
browser compare b
values.
Only if both the a and b values are the same does the browser consider the c value.
A specificity score of 1-0-0 is more specific than 0-2-2.
In the code above, selector a.myclass
includes a class attribute,
which means that the specificity of the style is 0-1-0.
0 is for id values, 1 is for other attributes, 0 is for element names.
The browser finds a value for the color
property when rendering an a element
that has been assigned to the myclass
class. For all other a elements, the
value from the other style will be used.
Example 2
When there are values defined in styles with the same specificity, the browser selects the value based on the order.
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
a.myclass1 {<!-- w ww . jav a 2s .c o m-->
color: black;
}
a.myclass2 {
color:white;
background:grey;
}
</style>
</head>
<body>
<a href="http://java2s.com">website</a>
<p>This is a paragraph.</p>
<a class="myclass1 myclass2" href="http://w3c.org">W3C</a>
</body>
</html>