Sobes.tech
Middle

How do you organize CSS isolation in Vue components in your projects?

sobes.tech AI

Answer from AI

Used several approaches depending on the project scale and requirements:

  1. Scoped CSS: The most common method in Vue. Styles are applied only to the current component's elements by automatically adding unique attributes to CSS selectors and DOM elements.

    <template>
      <div class="container">
        Hello, Vue!
      </div>
    </template>
    
    <style scoped>
    /* This style will only apply to the div with class container inside this component */
    .container {
      color: blue;
    }
    </style>
    
  2. CSS Modules: Allow creating local CSS classes that are automatically generated with unique names. Imported as an object in JavaScript. Provide explicit style localization.

    <template>
      <div :class="$style.container">
        Hello, Modules!
      </div>
    </template>
    
    <style module>
    /* The 'container' class will have a unique name during build */
    .container {
      color: green;
    }
    </style>
    
  3. CSS-in-JS (with libraries like Emotion or Styled Components via plugins): Styles are written directly in JavaScript/TypeScript. Provide strong isolation and dynamic styles but may increase bundle size and complexity.

    // Pseudocode example with a hypothetical library
    import styled from 'vue-styled-components'; // Example import
    
    const StyledDiv = styled.div` // Creating a styled component
      color: purple;
    `;
    
    export default {
      components: {
        StyledDiv,
      },
      template: `<styled-div>Hello, CSS-in-JS!</styled-div>`,
    };
    
  4. Naming Conventions (BEM): Using strict naming conventions like Block-Element-Modifier. Does not provide technical isolation through the framework but improves readability and predictability.

The choice of method depended on:

  • Team size.
  • Component complexity.
  • Need for style reusability.
  • Accepted standards in the project.

Most often, I used scoped for most components due to its simplicity and efficiency. CSS Modules were used for more complex cases requiring stricter localization or dynamic classes. CSS-in-JS was rarely used, mainly in projects where it was already used or there was a clear need. Naming Conventions always complemented other approaches.