Most developers use class and ID selectors on the body
element to add specific styles to specific pages. This is a recommended best practice that should be used either to have more control over the final layout or to give more control to your users thanks to user style sheets. However, as with many CSS techniques, this practice has been overused by many CMS applications so that now we can actually have a body
element with several classes applied to it, such as <body class="class1 class2 classn"></body>
. How these multiple classes are handled by browsers from a cascading perspective?
- if classes have no conflicting CSS rules, then the final styles will be the sum of all styles specified in each class:
.class1 { font-size: 76%; } .class2 { background: gray; } .classn { padding: 1em; }
- if classes have conflicting rules, then the final styles will be calculated according to cascade and specificity, that is:
- declarations with the
!important
statement have the precedence over other rules.class1 { font-size: 76% !important; /* winner */ } .class2 { font-size: 100%; }
- more specific selectors have the precedence over less specific selectors
html body.class1 { font-size: 76%; /* winner */ } body.class2 { font-size: 100%; }
- if the above points don't return a winner, then the class that comes later in the source will be the winner.
.class1 { font-size: 76% !important; } .class2 { font-size: 100% !important; /* winner */ }
- declarations with the