← Back to all tutorials

Component CSS (scoped)

Scope CSS to individual components using the scoped attribute — prevent styles from leaking to other parts of the app.

Component CSS (scoped)

By default, CSS in a .vue file is global — it applies to the entire app. The scoped attribute restricts styles to the current component only.

The Problem: Global CSS

<!-- ComponentA.vue -->
<style>
h2 { color: red; }   <!-- Affects ALL h2 elements in the entire app! -->
</style>

The Solution: Scoped CSS

<style scoped>
h2 { color: red; }   <!-- Only affects h2 elements in THIS component -->
</style>

Adding scoped tells Vue to add a unique data attribute to the component's elements and scope the CSS selectors to match only those elements.

How Scoped CSS Works

<!-- What Vue generates: -->
<h2 data-v-7ba5bd90>Title</h2>

<style>
h2[data-v-7ba5bd90] { color: red; }
</style>

Vue adds a unique attribute like data-v-7ba5bd90 to every element in the component and appends the same attribute selector to the CSS. This ensures the styles only match elements in this specific component.

Global vs Scoped

FeatureGlobalScoped
Applies toEntire applicationThis component only
Can affect childrenYesOnly the root element of children
Use forBase styles, resets, global utilitiesComponent-specific styles

Key Takeaways

  • Add scoped to the <style> tag to scope CSS to the current component
  • Scoped CSS works by adding unique data attributes and attribute selectors
  • Use global styles for base/reset CSS; scoped styles for component-specific styling