How to Override Bootstrap CSS
There may be instances where you want to customize or override the default styles provided by Bootstrap to match your project’s specific design requirements. In this article, we will explore how to override bootstrap styles in CSS.
What is override style?
If we set styles in Bootstrap and CSS for the same element, whichever has higher specificity will display the style. Bootstrap utilizes a hierarchical system of classes, with each subsequent class in the hierarchy having a higher specificity. If we give CSS style as normal, it is low specificity than bootstrap so it will display bootstrap styles.
How do override?
We can override Bootstrap in CSS in two ways,
Override using inline style
Inline CSS style has higher specificity than bootstrap so it will display CSS styles directly.
For example:
<div class="bg-primary" style="background-color: red;">HELLO</div>
Output:
In this example, we have created a <div>. We have linked Bootstrap via the cdn link, so we have set the Bootstrap background-color class to “bg-primary”. This class sets the blue background color. And in CSS we have set red background color using inline style. See the output, the div’s background is displayed in red color because inline style is high specificity than bootstrap.
!important keyword
You can use the “!important” keyword to override Bootstrap if you use internal or external styles.
Example:
<div class="bg-primary">HELLO</div>
CSS:
div{
background : red !important;
}
Output :
In this example, we have created a <div>. We have used the “!important” keyword for the CSS “background” property, so it displays the styles of the CSS with higher specificity than the bootstrap class.
There are instances when Bootstrap’s styles employ the !important rule to ensure consistency and functionality across different components. Overriding these styles can be more challenging, as the !important declaration takes precedence over other rules. In such cases, you may need to modify Bootstrap’s source code directly or use JavaScript to apply custom styles dynamically.
!important keyword using Multiple Styles
If you want to override multiple styles, use the “!important” keyword for all CSS properties you want to override.
<div class="bg-primary text-danger" >HELLO</div>
CSS:
div{
background: blue !important;
color: black !important;
}
Output:
In the above code, we have used the “!important” keyword to override both the “background” and “color” properties.