Insights
Various factors come into play (as is often the case), but the key sequence for you to consider is as follows:
- Styles with the highest specificity take precedence
- If multiple styles have the same specificity, the most recently declared one is applied
The hierarchy of selectors [along with the impact on specificity] is as follows:
- Tag
- Class
- ID
- Inline styles (using
style=""
)
!important
- Tag +
!important
- Class +
!important
- ID +
!important
- Inline styles +
!important
Tests have indicated that having 256
classes on a single element/selector can hold higher specificity than an ID. However, in practical scenarios, the number of classes used in conjunction with their position in the CSS file (avoiding excessive use of #ID) is a more common approach to styling.
For further understanding on specificity, refer to:
Illustration
HTML:
<div id="johnny" class="walker whisky"> -- </div>
CSS:
/* Example One */
div { border-color: red; } // Border color is red
.whisky { border-color: brown; } // Border color changes to brown
#johnny { border-color: black; } // Border color turns black
div#johnny { border-color: red; } // Reverts back to red
.walker { border-color: green !important; } // Now the border color is green
/* Example Two */
.whisky {border-color: brown; }
.whisky.walker {border-color: green; }
// The color is green
/* Example Three */
.whisky.walker {border-color: brown; }
.whisky {border-color: green !important; }
// Still green
Hope this explanation proves helpful.