How to Fix Bootstrap Overriding Custom CSS Quickly
!important sparingly to ensure your styles apply.Why This Happens
Bootstrap styles override custom CSS mainly because of CSS rules about order and specificity. When two styles target the same element, the one that comes later in the code or has stronger selectors wins. Bootstrap's CSS usually loads before your custom styles or uses selectors that are more specific, so it takes priority.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Broken Example</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"> <style> .btn { background-color: green; color: white; } </style> </head> <body> <button class="btn btn-primary">Click Me</button> </body> </html>
The Fix
To fix this, place your custom CSS after the Bootstrap CSS link so it loads later and overrides Bootstrap. Also, use more specific selectors to increase priority. If needed, use !important carefully to force your styles.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fixed Example</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"> <style> button.btn.btn-primary { background-color: green !important; color: white !important; } </style> </head> <body> <button class="btn btn-primary">Click Me</button> </body> </html>
Prevention
Always load your custom CSS after Bootstrap's CSS file. Use specific selectors that match the elements you want to style. Avoid overusing !important because it can make debugging harder. Consider using browser DevTools to inspect which styles apply and adjust accordingly.
Also, organize your CSS files clearly and test changes in different screen sizes to keep your design consistent and responsive.
Related Errors
Other common issues include:
- Custom CSS not loading: Check file paths and order of CSS links.
- Bootstrap JavaScript conflicts: Ensure scripts load in correct order and no duplicate libraries.
- Specificity wars: When multiple styles compete, use more specific selectors or CSS variables.