Guideline #1: Understanding CSS file processing order
It's essential to grasp the concept that CSS files are processed from top to bottom, hence the name "Cascading Style Sheet." When combining bootstrap files with custom ones, the styles defined later will take precedence due to their positioning in the file.
Consider this example:
// Bootstrap declaration
.pt-0 {
padding-top: 0 !important;
}
// Custom styles
.pt-10 {
padding-top: 10rem !important;
}
Both styles have the same property (padding-top
) and utilize !important
. Thus, the styles loaded later will prevail!
A similar principle is evident in this scenario where .pt-lg-0
is defined after .pt-5
in the file:
<div class="pt-5 pt-lg-0">...</div>
The specificity of .pt-5
versus .pt-lg-0
is governed by their position in the stylesheet.
Guideline #2: Priority based on selector specificity
In situations where multiple selectors target the same property, the one with higher specificity will take precedence.
For instance, given the following layout:
<div id="test-container" class="container">
<div class="pt-10 pt-lg-0">
...
</div>
</div>
And corresponding styles:
.container#test-container .pt-10 {
padding-top: 0rem !important;
}
.container .pt-10 {
padding-top: 5rem !important;
}
.pt-10 {
padding-top: 10rem !important;
}
In this scenario, the padding top value will be 0rem due to the higher specificity of the ID selector.
Guideline #3: Media queries and specificity
Media queries do not impact specificity levels within stylesheets. Regardless of breakpoints, styles are governed by their position in the file and specificity rules.
Therefore, the .pt-10
class will consistently override .pt-lg-0
due to the order of definition in alignment with Rule #1.
Recommendation
To achieve the desired outcome, avoid using !important
in your custom class:
.pt-10 {
padding-top: 10rem;
}
This approach ensures:
- Since your custom style loads after bootstrap, and there's no conflicting padding-top definition, your 10rem value will apply correctly.
- At larger breakpoints, the
.pt-lg-0
style from bootstrap, with !important
, will take precedence over your 10rem style. Introducing !important
to your 10rem style could create specificity conflicts.
Demo: https://jsfiddle.net/davidliang2008/9sqn4xch/16/