When working with Single File Components (.vue files), styling can easily bleed into other elements.
By default, any CSS you write inside a <style> tag is globally applied to the entire application.
Vue provides a powerful solution to this problem called "Scoped Styling".
To restrict CSS to only affect the current component, add the scoped attribute to the style tag.
When you do this, Vue magically generates a unique data attribute (like data-v-f3f3eg9) for the component.
It then appends this attribute to your CSS selectors under the hood, ensuring perfect isolation.
<template> <div class="example">hi</div> </template><style scoped> .example { color: red; } </style>
If you inspect the DOM in the browser, you will see how Vue protects your styles.
The code from the example above will be compiled by Vue's build tools into something like this:
<style>
.example[data-v-f3f3eg9] {
color: red;
}
</style>
<div class="example" data-v-f3f3eg9>hi</div>
This guarantees that .example classes in other components will remain completely unaffected!
Sometimes you need a scoped style to affect elements inside a child component.
By default, scoped styles do not leak down into child components.
To bypass this safely, use the :deep() pseudo-class.
<style scoped>
.a :deep(.b) {
/* This will affect .b elements inside child components */
color: blue;
}
</style>
You are not forced to choose one or the other.
You can safely include both a global <style> tag and a <style scoped> tag within the exact same component!
How does Vue achieve CSS scoping behind the scenes?
Which pseudo-class allows scoped styles to bleed down into nested child components?