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>