I'm trying to use Bootstrap in a Vue component, and I want all CSS to be scoped. I tried something like this:
<style scoped>
@import "~bootstrap/dist/css/bootstrap.css";
@import "~bootstrap-vue/dist/bootstrap-vue.css";
</style>
But it doesn't seem like the css is scoped. Is there any way to do that?
<style scoped src="~bootstrap/dist/css/bootstrap.css"></style>
<style scoped src="~bootstrap-vue/dist/bootstrap-vue.css"></style>
Update: a hack using SCSS
Reason why the first solution won't work:
With scoped, the parent component's styles will not leak into child components.
If you want a selector in scoped styles to be "deep", i.e. affecting child components, you can use the >>> combinator
from the Vue doc for scoped CSS
The modal you mentioned is apparently not being controlled by the component where you imported bootstrap. Perhaps it's a child component. Perhaps you're using the jquery version of Bootstrap modal. Either way, the data attributes won't be added to the modal.
In order to solve this, you need Deep Selector. (you may read about it in more detail in https://vue-loader.vuejs.org/en/features/scoped-css.html)
Here's how I would import the entire Bootstrap CSS using SCSS. (I think it's impossible to do this using pure CSS only.)
<template>
<div class="main-wrapper">
/* ... */
</div>
</template>
<style scoped lang="scss">
.main-wrapper /deep/ {
@import "~bootstrap/dist/css/bootstrap.min";
}
</style>
Some pre-processors, such as Sass, may not be able to parse >>> properly. In those cases you can use the /deep/ combinator instead - it's an alias for >>> and works exactly the same.
The generated CSS would be similar to
.main-wrapper[data-v-656039f0] .modal {
/* some css... */
}
.. which is what you want.
BUT, I gotta say, importing the entire Bootstrap CSS is a really bad practice. Try to import only and exactly what you are going to use from bootstrap-sass instead.
This solution is hacky. But it's the only way I know that can work for your use case.