--- title: Use Class Selectors in Scoped CSS for Performance impact: MEDIUM impactDescription: Element selectors in scoped CSS are slower because browsers must check both the element type and data attribute type: efficiency tags: [vue3, sfc, scoped-css, performance, css-selectors] --- # Use Class Selectors in Scoped CSS for Performance **Impact: MEDIUM** - When Vue compiles scoped CSS, it adds attribute selectors to every rule. Element selectors combined with attribute selectors (e.g., `p[data-v-xxx]`) are significantly slower for browsers to match than class selectors with attributes (e.g., `.text[data-v-xxx]`). ## Task Checklist - [ ] Prefer class selectors over element selectors in scoped styles - [ ] Avoid deeply nested element selectors in scoped CSS - [ ] Use BEM or similar naming conventions to ensure unique class names - [ ] For heavy styling, consider CSS modules or utility-first approaches **Problematic Code:** ```vue ``` **Correct Code:** ```vue ``` ## How Scoped CSS Compiles Vue transforms scoped CSS by adding data attributes: ```css /* What you write */ p { color: red; } .text { color: blue; } /* What Vue generates */ p[data-v-7ba5bd90] { color: red; } .text[data-v-7ba5bd90] { color: blue; } ``` Browser CSS matching for `p[data-v-xxx]`: 1. Find all `

` elements (element lookup) 2. Check each for the `data-v-xxx` attribute (attribute check) Browser CSS matching for `.text[data-v-xxx]`: 1. Find all elements with class `text` (class lookup - optimized) 2. Check each for the `data-v-xxx` attribute Class lookups are highly optimized in modern browsers, making option 2 faster. ## When Performance Matters This optimization matters most when: - Rendering large lists (100+ items) - Complex component trees - Animation-heavy interfaces - Mobile devices with limited CPU ```vue ``` ## Acceptable Element Selectors For small components with few elements, element selectors are fine: ```vue ``` ## CSS Modules Alternative For performance-critical components, CSS modules avoid the attribute selector entirely: ```vue ``` ## Reference - [Vue Loader Scoped CSS](https://vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements) - [CSS Selector Performance](https://csswizardry.com/2011/09/writing-efficient-css-selectors/)