tezvyn:

Vue Scoped CSS: Keep Your Styles Local

AI-drafted, machine-checkedSource: vuejs.orgbeginner

Vue's Scoped CSS prevents styles from leaking out of a component. It adds a unique data attribute to your component's HTML and rewrites CSS to target it, ensuring styles only apply locally.

WHY IT EXISTS In large applications, global CSS is fragile. A style for .card in one part of the app can unintentionally affect a .card somewhere else, leading to style conflicts and complex naming conventions like BEM. Scoped CSS was created to solve this by making styles local to a component by default.

THE MENTAL MODEL Think of Scoped CSS as giving each component its own private stylesheet, like putting up walls between rooms in a house. The paint color in one room doesn't bleed into the next. Vue achieves this not with native Shadow DOM, but by rewriting your code at build time to enforce this separation.

HOW IT WORKS When you add the scoped attribute to a <style> tag in a Vue Single-File Component (SFC), the build process does two things. First, it adds a unique data attribute, like data-v-f3f3eg9, to every element in that component's template. Second, it rewrites every CSS selector in your scoped style block to include that attribute. A rule like .example { color: red; } becomes .example[data-v-f3f3eg9] { color: red; }, locking the style to the component.

WHEN TO USE IT Use scoped styles by default for almost all components. It is the idiomatic Vue way to create encapsulated, reusable UI pieces. It lets you focus on a component's styles without worrying about side effects across your application, which simplifies CSS management significantly.

WHEN NOT TO USE IT Avoid it for truly global styles like CSS resets, utility classes, or theme variables; use a separate, non-scoped <style> tag for those. Be aware that scoped styles don't apply to content injected via v-html or passed through <slot> from a parent. You must explicitly opt-in to styling them.

ONE CANONICAL EXAMPLE To style content inside a child component from a parent, you must use the :deep() pseudo-class. A parent style like .wrapper :deep(.child-class) { color: blue; } will successfully style an element with .child-class inside a child component. Without :deep(), the style would not apply because the child's elements don't have the parent's unique data attribute. Similarly, use the :slotted() pseudo-class to style content passed into a component's slot.

Read the original → vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.