Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 87 ยท Reusability, Transitions and Styling

Scoped CSS and CSS Modules

Keep component styles from leaking with scoped CSS, reach into children with :deep and ::v-slotted, use CSS Modules, and drive styles from state with v-bind in CSS.

CSS is global by default. A rule such as .title { color: crimson } written for one component also hits every other element in the app that happens to use the class title. On a small page you notice and rename. In a large app with many authors it becomes a source of "why did this heading change color?" bugs.

Vue's single-file components (SFCs) offer two ways to keep styles local: scoped CSS (<style scoped>) and CSS Modules (<style module>). Both are features of the SFC compiler, so they need a build step. The examples in this lesson run in the browser, so for each one we show the SFC version read-only and then a runnable version where we write by hand exactly what the compiler would generate. That makes the mechanism visible, and it is a good way to understand what is really happening.

This lesson assumes you know what an SFC is (Single-File Components). Both styling features here are compile-time transforms. Nothing in the Vue runtime knows about scoped.

Scoped CSS in an SFC

Add the scoped attribute to a <style> block and its rules apply only to elements of that component's own template.

VUE
<!-- ProfileCard.vue -->
<template>
  <div class="card">
    <h3 class="title">{{ name }}</h3>
  </div>
</template>

<script setup>
defineProps({ name: String })
</script>

<style scoped>
.card { border: 1px solid #ccc; padding: 8px; }
.title { color: crimson; }
</style>

Any other component can also have a .title class with a different look. They do not interfere.

How scoping works

When the compiler processes a component with a scoped style, it generates a short unique id from the file (for example 7ba5bd90) and does two things:

  1. Every element in the component's own template gets an attribute data-v-7ba5bd90.
  2. Every selector in the style block gets the same attribute selector added to its last compound selector.
CSS
/* what you wrote */
.card .title { color: crimson; }

/* what the browser receives */
.card .title[data-v-7ba5bd90] { color: crimson; }
flowchart LR
  A["ProfileCard.vue"] --> B["SFC compiler<br/>creates id 7ba5bd90"]
  B --> C["Template: every element<br/>gets data-v-7ba5bd90"]
  B --> D["CSS: selectors end with<br/>[data-v-7ba5bd90]"]
  C --> E["Browser matches by<br/>plain attribute selectors"]
  D --> E

Scoping is ordinary CSS attribute matching. There is no runtime magic and no Shadow DOM.

Because the marker is on the last part of the selector, a rule such as .card .title matches only .title elements that this component rendered. A .title from a child component does not carry the marker, so the rule skips it.

Try it: scoping by hand

Here are two components that both use the class title for different colors. Each template carries its own marker attribute, and each rule ends with the same marker, exactly like compiled output. The <pre> below prints the DOM that was rendered, so you can read the markers.

Two components, one class name

Both headings use class="title", yet one is crimson and the other teal. Delete the [data-v-...] parts from the two rules and the last one wins for both: that is the global-CSS problem scoping removes.

Things to know about scoped styles

  • A child's root element belongs to both scopes. The root node of a child component receives the child's marker and the parent's marker, so a parent can style the child's outer element (for example to add a margin). Elements deeper inside the child get only the child's marker.
  • Prefer class selectors. p { color: red } becomes p[data-v-...], which is slower for browsers to match than .my-class[data-v-...], and it is easy to break by moving markup around.
  • Content inserted with v-html has no marker, because it never went through the compiler. Scoped rules do not reach it; use :deep() (below) for those elements.
  • Specificity grows by one attribute selector. A scoped rule is slightly more specific than the same rule unscoped, which occasionally surprises people who override library styles.

Reaching across scopes: :deep, :slotted, :global

Scoping is a boundary, and sometimes you need to cross it on purpose. Three pseudo-selectors, understood only by the Vue SFC compiler, do that.

VUE
<style scoped>
/* style an element inside a child component */
.wrapper :deep(.inner) { background: gold; }

/* in a component with a slot: style content the PARENT put in the slot */
:slotted(.tag) { font-weight: bold; }

/* a rule with no scoping at all, inside a scoped block */
:global(body.dark) .card { background: #222; }
</style>
You write Compiled to (roughly) Meaning
.wrapper :deep(.inner) .wrapper[data-v-x] .inner The marker moves to the left part, so the right part can be any descendant, including inside children
:slotted(.tag) .tag[data-v-x-s] Matches elements passed in through <slot> (they belong to the parent's scope, not yours)
:global(.x) .x No marker at all

(::v-deep() and ::v-slotted() are older spellings of the same features. The short forms are preferred in current Vue.)

The next example hand-writes those compiled rules. The child's .inner element carries only the child's marker. A rule ending in the parent's marker does not reach it; the "deep" rule, whose marker is on the left, does. Slotted content belongs to the parent, so it is styled by a rule using the child's slotted marker.

Crossing the boundary with deep and slotted

Look at the preview: the child's paragraph has a gold background (the deep rule worked) but no red outline (a plain scoped rule cannot see into the child), and the slotted text is bold and purple.

:deep() is a power tool. Every use couples the parent to the internal markup of a child, so a refactor inside the child can silently break the parent's styles. Prefer giving the child a real prop, a slot, or a CSS custom property as its styling API, and keep :deep() for third-party components you cannot change.

CSS Modules

The second option renames the classes instead of adding attributes. Write <style module> and Vue exposes the generated class names through $style in templates:

VUE
<template>
  <span :class="[$style.badge, { [$style.big]: large }]">New</span>
</template>

<style module>
.badge { padding: 4px 12px; border-radius: 999px; background: var(--accent, #2a7de1); color: white; }
.big { font-size: 1.4rem; }
</style>

The compiler rewrites .badge to something like .badge_x7k2 (a hash of the file and class name) and makes $style.badge return that string. Two components can both have a .badge class without conflict, and unlike scoped CSS the selectors stay plain class selectors with no attribute added.

A few options:

  • <style module="classes"> gives the object a custom name, so you write classes.badge (handy when a component has several module blocks).
  • In <script setup>, call useCssModule() (or useCssModule("classes")) to read the same object.
  • Class names that never appear in the module object (for instance because you wrote a typo, $style.badgee) simply evaluate to undefined, so check the DOM when a style is missing.

Driving styles from state: v-bind() in CSS

Both approaches can use v-bind() inside a <style> block to connect CSS to reactive state:

VUE
<script setup>
import { ref } from 'vue'
const color = ref('#2a7de1')
</script>

<style scoped>
.badge { background: v-bind(color); }
.chip { border-color: v-bind('theme.border'); } /* quotes for JS expressions */
</style>

There is no runtime CSS generation here either. The compiler replaces v-bind(color) with var(--7ba5bd90-color) and makes the component set that CSS custom property as an inline style on its root element, updating it whenever color changes. Because custom properties inherit, every descendant sees it.

That means you can write the same thing by hand in a runtime-compiled app, which is what the next example does. It simulates a CSS Module (a plain object of class names) and uses a custom property for the color.

CSS Modules and v-bind by hand

Pick another color and the badge updates through the custom property alone. No class changes, no new stylesheet.

Which one should you use?

Approach Strengths Watch out for
<style scoped> Least ceremony: write normal CSS and normal class names Cross-scope styling needs :deep(); attribute selectors add specificity
<style module> Plain class selectors, explicit $style.x usage, easy to compose in JS Slightly more typing; typos fail silently
Global CSS (unscoped) Resets, typography, design tokens, utility classes Name collisions in large teams

Most apps combine them: a global stylesheet for tokens, resets and base typography, and scoped styles in components. The next lesson shows how to organize those layers, and Fallthrough Attributes explains how class on a child's root element merges with the child's own classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the SFC compiler do for <style scoped>?

    Scoping is attribute matching: the same generated marker is placed on the template's elements and on each selector. The browser's normal CSS rules do the rest.
  2. 2. A parent needs to style an element deep inside a third-party child component. Which scoped selector fits?

    :deep() moves the scope marker to the left part of the selector, so the right part may match any descendant, including elements rendered by children.
  3. 3. How does v-bind() in a style block pass a reactive value to CSS?

    The compiler turns v-bind(color) into var(--hash-color) and sets that custom property inline on the root element, updating it when the state changes.
  4. 4. What is $style in a component that has <style module>?

    Each class in the module block is renamed to a unique string, and $style.badge returns that string so you can use it in :class.

Summary

  • <style scoped> marks template elements with a data-v-xxxx attribute and ends each selector with the same attribute selector.
  • Scoped rules do not reach child components' inner elements, but a child's root element receives the parent's marker too.
  • :deep() crosses into children, :slotted() styles content passed through a slot, and :global() opts out of scoping.
  • Prefer class selectors in scoped styles, and prefer a prop, slot or CSS variable over :deep() for your own components.
  • <style module> renames classes and exposes them as $style (or a custom name, or useCssModule()).
  • v-bind() in CSS compiles to a custom property set on the component's root element.
  • All of this happens at compile time, so these features need an SFC build step.

Next: Styling Strategies