The custom stylesheet added to index.html is not taking precedence over the Bootstrap 5 styles applied through NPM

In my Vue 2 project, I encountered an issue with Bootstrap 5.3 when installed via NPM. My custom CSS stylesheet in the index.html file was not able to override Bootstrap's CSS.

Interestingly, I faced no problems when using Bootstrap from a CDN. Additionally, directly adding custom CSS within components successfully overrides Bootstrap's styles. It seems that only the global stylesheet in index.html is being overridden.

My main.js setup includes:

import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'

let Bootstrap = require('bootstrap')
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Vuex from 'vuex'
import store from './store'
import VueI18n from 'vue-i18n'

Vue.use(Vuex)
Vue.use(VueI18n)

Vue.use(Bootstrap)
Vue.use(BootstrapVue)
Vue.use(IconsPlugin)

new Vue({
    store: store, 
    router,
    i18n,
    beforeCreate() { this.$store.commit('initialiseStore');},
    render: h => h(App),
}).$mount('#app')

As for my index.html structure:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">

    <link rel="stylesheet" href="<%= BASE_URL %>media/css/layout.css?v2">
    <link rel="stylesheet" href="<%= BASE_URL %>media/css/mobile.css?v1">

To resolve the issue, I removed the stylesheet reference from index.html and included the following code in App.vue instead:

<style lang="scss">

@import '/media/css/layout.css';
@import '/media/css/mobile.css';

</style>

I am uncertain whether calling the custom stylesheet in App.vue is the recommended approach. Moreover, I am unsure if referencing Bootstrap in index.html is still necessary when it is installed via NPM. If so, how can I correctly reference Bootstrap from the node_modules folder?

Answer №1

There are two ways to incorporate bootstrap into your project: through npm or via CDN. It is not necessary to use both methods simultaneously. It is recommended to choose one method and stick with it throughout your application. For more information on using bootstrap, refer to the official documentation.

When importing or including bootstrap via CDN, remember to consider CSS precedence and specificity rules. Ensure that your most important stylesheets are imported last, like so:

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7974746f686f697a6b5b2e3528352b367a776b5d41783a">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">

<!-- Ensure your most critical styles are loaded last -->
<link rel="stylesheet" href="/mycustom.css">

You can also use imports as shown below:

import 'bootstrap/dist/css/bootstrap.css';

/* Ensure your most important styles are imported last */
import 'mycustomstyles.css';

If you opt for a hybrid approach, such as mixing imported styles with those added directly to the HTML, pay attention to how the imports are included in the page structure. In React, style imports typically appear at the end of the <head> element, giving them higher priority than CSS links defined within the HTML itself. Specificity plays a significant role here—inline and !important styles take precedence.

Keep in mind that if a bootstrap rule is marked as !important, it will override your rule even if the stylesheet is imported or included afterward unless you also use !important for the same target element or apply inline styles.

To delve deeper into specificity, check out this helpful answer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experience the smooth CSS3 transition effects on iOS devices such as iPhones and iPads. Elevate the appearance of DOM objects with

I have a basic image contained within a div tag. I use JavaScript to add a transition effect to the div element: <div style="transition: opacity 0.8s linear; opacity: 0.5;"><img src="..." /></div> At the end of the transition duration ...

Vite is only executable as `npm run dev` and is not directly runnable in the terminal

I have encountered a strange issue with my project. Here is the sequence of steps I took: npm create vite@latest cd into the project folder. npm i npm run dev While everything seems to be working fine, the vite.config.js file is not being generated. When ...

Scaling boxes responsively according to screen size utilizing Bootstrap

Creating a portfolio website with a carousel section to display completed projects in a 2x2 grid layout, transitioning to a 1x4 on smaller screens is proving to be quite challenging. After trying various methods from Bootstrap documentation and YouTube tut ...

What steps can I take to troubleshoot and resolve any errors that arise while using Strapi

I'm in the process of building a portfolio website using Gatsby and Strapi. Everything was going smoothly until I attempted to input a large amount of data into strapi, resulting in an error message stating "An error occurred" and causing the developm ...

Display a "Loading" image in the gallery before anything else loads

Can a animated loading gif be implemented to load before the gallery images, or would it serve no purpose? The image will be loaded as a background using CSS. <link rel="stylesheet" href="loading.gif" /> Appreciate your help! ...

One way to generate div elements based on the number in an input field when a button is clicked, but ensuring it only happens once

What I am attempting to achieve is: Retrieve data from a JSON file upon button click. Display the data in separate boxes, each one different for every element of the array. For instance, if the JSON provides 3 rows of data, there should be 3 distinct box ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

What causes a webpage to overflow when using the position:absolute property?

Despite my understanding that an element positioned absolutely should be removed from the normal content flow, why does it still cause the page to overflow? Running the code snippet below reveals a horizontal scrollbar, which I didn't expect. .rela ...

Issue: Module 'request-promise' not found

I have been trying to execute my nodejs code on Snowflake Server. The code seems fine but I keep encountering the following error: `Error:` Cannot find module 'request-promise' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:6 ...

What is the best way to combine height and min-height in order to ensure that a div always extends to the bottom and keeps

I've tried multiple suggestions without success so far. In my website, I have a main section with white background centered on the page. It stretches nicely to the bottom using flex. See image: https://i.sstatic.net/RmJ2o.png However, there's a ...

Utilize Vue to save user inputs and dynamically display them in another field

I'm struggling with setting up methods for this. My goal is to have the input data displayed on my table only after clicking the save button. Currently, it's displaying on the table without needing to click save. Can someone assist me with the co ...

Using CSS to showcase div elements with varying dimensions

How can I arrange divs with varying heights to be positioned close together, regardless of their height, and with a specific margin similar to buildings? I am aiming for a layout like the one on this website . I tried using float:left but it only float ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

The lower border is unresponsive in the CSS/HTML code currently in use

Currently diving into the world of Web Development, I find myself tackling the CSS part. My latest challenge involves adding a bottom border to an element, but no matter what I try, the border just won't show up. I've scoured resources for soluti ...

Error: The W3C Validator has identified a parsing issue related to the opacity setting of

After putting my stylesheet through the CSS validator at W3C, I encountered only one error which read "Parse Error Opacity=60". The issue seems to be in this specific part of the CSS code: /*Navigation Link styling */ #Nav a:link, a:visited { display: inl ...

Can @keyframes be iterated through CSS (particularly Stylus)?

Here is some Stylus code I'm working with: for i in (1..3) .l:nth-child({i}) opacity (i / 5) When executed, the output looks like this: .l:nth-child(1) { opacity: 0.2; } .l:nth-child(2) { opacity: 0.4; } .l:nth-child(3) { opacity: 0.6; } ...

Setting up the NPM configuration in Intellij IDEA for proxy in Angular 2

How can I set up Intellij IDEA to run an npm Angular 2 conf with a proxy as an argument by clicking on it? I know I can do it via the terminal using the command ng serve --proxy-config proxy.conf.json, but it would be much easier to configure it in Intelli ...

The text manipulates the canvas position and changes the location of mouse hover interaction

I am trying to achieve a similar header layout like the one shown on this page. However, when I insert some text within the header section: <div id="large-header" class="large-header"> <h1 style="font-size:150%;">Dummy Text</h1> ...

What are the advantages of combining a library (using Rollup or Webpack) instead of simply transpiling it with Babel?

When developing a library in JavaScript, what are the benefits of using tools like Rollup or Webpack for bundling rather than just transpiling with Babel? One potential advantage could be that by bundling, you ensure that your dependencies are packaged eff ...

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...