How to use CSS modules in Vue

CSS modules in Vue provide scoped styling with automatic class name generation, preventing style conflicts while maintaining full CSS feature support. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented CSS modules in Vue components for theme systems, component libraries, and enterprise applications requiring strict style isolation. From my expertise, the most effective approach is to use the module attribute in Vue’s style tags. This method provides automatic scope isolation, supports all CSS features including preprocessors, and integrates seamlessly with Vue’s template system.

Use module attribute in style tags to enable CSS modules with automatic scoped class names.

<template>
  <button :class="[$style.button, { [$style.primary]: isPrimary }]">
    {{ label }}
  </button>
</template>

<script setup>
const props = defineProps(['label', 'isPrimary'])
</script>

<style module>
.button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
}

.primary {
  background-color: #007bff;
  color: white;
}
</style>

CSS modules in Vue are enabled by adding the module attribute to style tags. Vue automatically generates unique class names and exposes them through the $style object in templates. Access classes using $style.className syntax, and combine classes using array syntax or object syntax for conditional styling. CSS modules work with preprocessors like Sass and support all CSS features including pseudo-classes, media queries, and CSS custom properties.

Best Practice Note:

This is the same approach we use in CoreUI Vue components for maintainable style isolation and theme customization. Use named modules with <style module="classes"> for multiple CSS module blocks in one component, and combine with computed properties for complex conditional styling logic.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Convert a Map to an Array in JavaScript
How to Convert a Map to an Array in JavaScript

How to validate an email address in JavaScript
How to validate an email address in JavaScript

How to Detect a Click Outside of a React Component
How to Detect a Click Outside of a React Component

JavaScript printf equivalent
JavaScript printf equivalent

Answers by CoreUI Core Team