Vue Scoped Styling

Vue Scoped Styling

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".


Using the Scoped Attribute

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.

Scoped Style Syntax:

<template>
  <div class="example">hi</div>
</template>

<style scoped> .example { color: red; } </style>


How Scoped Styling Compiles

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:

Compiled Output:

<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!


Deep Selectors

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.

Deep Selector Example:

<style scoped>
.a :deep(.b) {
  /* This will affect .b elements inside child components */
  color: blue;
}
</style>

Global and Scoped Together

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!


Exercise 1 of 2

?

How does Vue achieve CSS scoping behind the scenes?

Exercise 2 of 2

?

Which pseudo-class allows scoped styles to bleed down into nested child components?