Vue Scoped Styling

Keep your component styles isolated and organized

๐ŸŽจ What is Scoped Styling?

Scoped styling in Vue ensures that CSS styles apply only to the current component, preventing style conflicts. Add the scoped attribute to your style tag to keep styles isolated and maintainable.


<template>
  <div class="card">
    <h2>My Card</h2>
  </div>
</template>

<style scoped>
.card {
  background: lightblue;
  padding: 20px;
}
</style>
                                    

Key Scoped Styling Features

๐Ÿ”’

Isolation

Styles only affect current component

<style scoped>
h1 { color: blue; }
</style>
๐ŸŽฏ

No Conflicts

Prevents CSS class name collisions

<style scoped>
.button { color: red; }
</style>
๐Ÿงน

Clean Code

Keeps styles organized per component

<style scoped>
.container { margin: 10px; }
</style>
โšก

Easy Maintenance

Styles live with component code

<style scoped>
.card { padding: 15px; }
</style>

๐Ÿ”น Basic Scoped Styling

Add the scoped attribute to keep styles within the component:

<template>
  <div class="greeting">
    <h1>Hello Vue!</h1>
    <p>This text is styled locally.</p>
  </div>
</template>

<style scoped>
.greeting {
  background: #f0f0f0;
  padding: 20px;
  border-radius: 8px;
}

h1 {
  color: #42b883;
  margin: 0;
}

p {
  color: #35495e;
}
</style>

Output:

Hello Vue!

This text is styled locally.

๐Ÿ”น Scoped vs Global Styles

Compare scoped and global styling approaches:

๐Ÿ”ธ Scoped Styles (Recommended)

<template>
  <button class="btn">Click Me</button>
</template>

<style scoped>
.btn {
  background: #42b883;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
}
</style>

๐Ÿ”ธ Global Styles

<template>
  <button class="btn">Click Me</button>
</template>

<!-- Without scoped - affects all components -->
<style>
.btn {
  background: #42b883;
  color: white;
}
</style>

๐Ÿ”น Deep Selectors

Style child components using deep selectors:

<template>
  <div class="wrapper">
    <ChildComponent />
  </div>
</template>

<style scoped>
/* Style elements in child components */
.wrapper :deep(.child-class) {
  color: red;
}

/* Alternative syntax */
.wrapper::v-deep .child-class {
  color: red;
}
</style>

๐Ÿ”น Slotted Content Styling

Style content passed through slots:

<template>
  <div class="container">
    <slot></slot>
  </div>
</template>

<style scoped>
/* Style slotted content */
.container :slotted(p) {
  color: blue;
  font-size: 16px;
}

.container :slotted(.highlight) {
  background: yellow;
}
</style>

๐Ÿ”น Mixing Scoped and Global

Use both scoped and global styles in one component:

<template>
  <div class="component">
    <h2>Mixed Styles</h2>
  </div>
</template>

<!-- Scoped styles -->
<style scoped>
.component {
  padding: 20px;
}
</style>

<!-- Global styles -->
<style>
body {
  font-family: Arial, sans-serif;
}
</style>

๐Ÿง  Test Your Knowledge

What attribute makes styles scoped in Vue?