Vue.js course · Module 6: Components

Scoped Styles and CSS Modules

6 min read ·
In this lesson5

Style isolation in components works like the bulkheads between habitat modules - whatever happens in one compartment doesn't get into the neighboring ones.

Two components in the base use a .card class: one is a module card, the other a crew member card. Plain CSS applies to the whole page, so a rule written in one file repaints the cards in both. Vue offers several levels of isolation, and today you'll get to know each of them.

Scoped Styles

You know the scoped attribute from the Launch Zone: the rules in such a block apply only to the elements of the current component. Let's start with a card whose styles won't leak outside the file:

<template>
  <div class="card">
    <h3 class="title">{{ title }}</h3>
  </div>
</template>

<style scoped>
/* Only for this component */
.card {
  border: 1px solid #ccc;
  padding: 1rem;
}

.title {
  color: #333;
}
</style>

Vue adds an attribute such as data-v-7ba5bd90 to every element of the component and turns the .card selector into .card[data-v-7ba5bd90]. A crew member card in another file gets a different attribute, so this rule won't touch it. There is one deliberate exception: the root element of a child component is affected both by the child's styles and by the parent's scoped styles, so the parent can position it in its layout.

:deep() - a look inside the child

Sometimes, though, the parent has to style an element located deeper inside a child component. That's what the :deep() pseudo-selector is for:

<style scoped>
/* Deep selector - affect child components */
.card :deep(.child-class) {
  color: blue;
}
</style>

The compiler turns this rule into .card[data-v-7ba5bd90] .child-class. The attribute stays only on .card, so .child-class also matches elements inside the children. The older >>> and /deep/ forms come from Vue 2 - the Vue 3 compiler still understands them, but it warns that they are deprecated and tells you to use :deep().

:slotted() and :global()

Two more pseudo-selectors deal with content from outside the component. A slot is a place in a child's template into which the parent puts its own content - you'll learn about it in Module Storage. Such content belongs to the parent, so the child's scoped styles don't cover it by default:

<style scoped>
/* Slotted content */
:slotted(.slot-class) {
  font-weight: bold;
}

/* Global in scoped */
:global(.global-class) {
  background: yellow;
}
</style>

:slotted() directs a rule at the content inserted through a slot, while :global() turns off isolation for a single rule, so .global-class will work on the whole page. Use global rules inside scoped styles sparingly, because they are an open door in the bulkhead.

CSS Modules

The second way to isolate styles is CSS Modules. A <style module> block turns every class into a unique, generated name, and in the template you reach it through the $style object and the :class directive:

<template>
  <div :class="$style.card">
    <h3 :class="$style.title">{{ title }}</h3>
    <p :class="[$style.text, $style.highlighted]">Description</p>
  </div>
</template>

<style module>
.card {
  border: 1px solid #ccc;
}

.title {
  color: #333;
}

.text {
  font-size: 14px;
}

.highlighted {
  background: yellow;
}
</style>

The square brackets apply two classes at once, because :class also accepts an array. The card class from this file has nothing to do with card in another component - both get different names. The difference from scoped is that isolation works through class names rather than attributes, and it covers only the elements to which you explicitly assign a class from $style. You can also read the generated names in the script with the useCssModule function:

<script setup>
import { useCssModule } from 'vue'

const styles = useCssModule()
console.log(styles.card) // e.g. "_card_1a2b3_2" - the name is generated by Vite
</script>

The name format depends on the build tool's configuration - by default Vite combines the class name, a hash of the content and the line number. A block can also get its own name, for example <style module="classes">, and then you write classes.card in the template.

Dynamic Styles

Sometimes a color should depend on the data, for example on the module type. The :style directive accepts an object, and its keys can also be CSS variables, meaning properties that start with two dashes:

<template>
  <div
    class="card"
    :style="{
      '--primary-color': primaryColor,
      '--border-width': borderWidth + 'px'
    }"
  >
    <h3>{{ title }}</h3>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const primaryColor = ref('#8b7355')
const borderWidth = ref(2)
</script>

<style scoped>
.card {
  border: var(--border-width) solid var(--primary-color);
  color: var(--primary-color);
}
</style>

The component sets the --primary-color and --border-width variables on its element, and the rule in <style scoped> reads them with the var() function. The stylesheet doesn't change - only the values of the variables change when the ref() containers change.

v-bind() in CSS

Vue can do the same thing more simply: the v-bind() function written directly into a CSS rule binds a value to a container from <script setup>:

<template>
  <div class="card">
    <input v-model="color" type="color" />
    <p>This text changes color!</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const color = ref('#8b7355')
</script>

<style scoped>
p {
  /* Reactive binding! */
  color: v-bind(color);
}
</style>

Pick a color in the field, and the text takes it on immediately. The compiler turns v-bind(color) into a CSS variable with a unique name, which Vue sets on the component's root element and updates on every change, so the stylesheet itself stays static.

Isolation Levels

From the widest to the narrowest reach: global styles without scoped apply to the whole page, <style scoped> to the elements of one component, CSS Modules only to elements with a class from $style, and an inline style through :style to one specific element. At NOVA LAB we write <style scoped> by default and reach for CSS Modules when class names are needed in the script - that's the starting point I recommend to you.

In the editor below, every component of the material settings panel has its own <style scoped> block. Change a color in one file and check that the other one stays unchanged. The panel also uses v-model on components, which you'll learn at the Communication Station.

Remember: scoped puts bulkheads around a module, CSS Modules give classes unique names, and v-bind() in CSS connects the look straight to the mission data.

Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'
import MaterialSettings from './MaterialSettings.vue'

const printSettings = ref({
  material: 'PLA',
  temperature: 210,
  speed: 50,
  layerHeight: 0.2
})

const extruderSettings = ref({
  flowRate: 100,
  retraction: 5
})

function savePrintSettings() {
  console.log('Print settings saved:', printSettings.value)
  alert('Settings saved!')
}

function saveExtruderSettings() {
  console.log('Extruder settings saved:', extruderSettings.value)
  alert('Extruder settings saved!')
}
</script>

<template>
  <div class="settings-lab">
    <div class="header">
      <h1>Material Settings - NOVA LAB</h1>
      <p class="subtitle">Component v-model</p>
    </div>

    <div class="info-panel">
      <h3>v-model in components</h3>
      <p><strong>v-model</strong> is shorthand for :modelValue + @update:modelValue</p>
      <p>You can use multiple v-model with different names: v-model:customName</p>
      <code class="code-example">
<!-- In the parent component -->
v-model="value"
v-model:customName="otherValue"

<!-- In the child component -->
defineProps(['modelValue', 'customName'])
emit('update:modelValue', newValue)
emit('update:customName', newValue)
      </code>
    </div>

    <div class="settings-grid">
      <!-- Single v-model -->
      <div class="settings-card">
        <h2>Basic print settings</h2>
        <MaterialSettings v-model="printSettings" />

        <div class="preview-section">
          <h4>Value preview:</h4>
          <pre>{{ JSON.stringify(printSettings, null, 2) }}</pre>
          <button @click="savePrintSettings" class="btn btn-save">
            Save settings
          </button>
        </div>
      </div>

      <!-- Multiple v-models -->
      <div class="settings-card">
        <h2>Extruder settings</h2>
        <MaterialSettings
          v-model="extruderSettings"
          :show-advanced="true"
        />

        <div class="preview-section">
          <h4>Value preview:</h4>
          <pre>{{ JSON.stringify(extruderSettings, null, 2) }}</pre>
          <button @click="saveExtruderSettings" class="btn btn-save">
            Save extruder settings
          </button>
        </div>
      </div>

      <!-- Direct input with v-model -->
      <div class="settings-card">
        <h2>Manual editing (JSON)</h2>
        <textarea
          v-model="printSettings.material"
          class="json-editor"
          placeholder="Edit material name..."
        ></textarea>
        <p class="info-text">
          Changes in the text field automatically update the printSettings object
        </p>
      </div>
    </div>

    <div class="summary-panel">
      <h2>Summary of all settings</h2>
      <div class="summary-grid">
        <div class="summary-item">
          <h4>Print settings</h4>
          <ul>
            <li>Material: <strong>{{ printSettings.material }}</strong></li>
            <li>Temperature: <strong>{{ printSettings.temperature }}°C</strong></li>
            <li>Speed: <strong>{{ printSettings.speed }}%</strong></li>
            <li>Layer height: <strong>{{ printSettings.layerHeight }}mm</strong></li>
          </ul>
        </div>
        <div class="summary-item">
          <h4>Extruder settings</h4>
          <ul>
            <li>Flow rate: <strong>{{ extruderSettings.flowRate }}%</strong></li>
            <li>Retraction: <strong>{{ extruderSettings.retraction }}mm</strong></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-lab {
  background: linear-gradient(135deg, #0a0e27 0%, #1a1e3f 100%);
  min-height: 100vh;
  padding: 2rem;
  color: #ffffff;
  font-family: 'Courier New', monospace;
}

.header {
  text-align: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #00ff88;
}

.header h1 {
  font-size: 2.5rem;
  color: #00ff88;
  text-shadow: 0 0 20px rgba(0, 255, 136, 0.5);
  margin: 0;
}

.subtitle {
  color: #00b4d8;
  font-size: 1.2rem;
  margin-top: 0.5rem;
}

.info-panel {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.info-panel h3 {
  color: #00b4d8;
  margin-top: 0;
}

.info-panel strong {
  color: #00ff88;
}

.code-example {
  display: block;
  background: rgba(0, 0, 0, 0.5);
  border-left: 4px solid #00ff88;
  padding: 1rem;
  border-radius: 5px;
  color: #00ff88;
  margin-top: 1rem;
  white-space: pre;
  overflow-x: auto;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.settings-card {
  background: rgba(0, 255, 136, 0.05);
  border: 2px solid #00ff88;
  border-radius: 10px;
  padding: 1.5rem;
}

.settings-card h2 {
  color: #00ff88;
  margin-top: 0;
  margin-bottom: 1.5rem;
}

.preview-section {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 2px solid rgba(0, 255, 136, 0.2);
}

.preview-section h4 {
  color: #00b4d8;
  margin-top: 0;
}

.preview-section pre {
  background: rgba(0, 0, 0, 0.5);
  padding: 1rem;
  border-radius: 5px;
  color: #00ff88;
  overflow-x: auto;
  border-left: 4px solid #00ff88;
}

.json-editor {
  width: 100%;
  min-height: 150px;
  background: rgba(0, 0, 0, 0.3);
  border: 2px solid #00b4d8;
  border-radius: 5px;
  padding: 1rem;
  color: #ffffff;
  font-family: 'Courier New', monospace;
  resize: vertical;
}

.json-editor:focus {
  outline: none;
  border-color: #00ff88;
  box-shadow: 0 0 10px rgba(0, 255, 136, 0.3);
}

.info-text {
  color: #00b4d8;
  font-size: 0.9rem;
  margin-top: 1rem;
}

.btn-save {
  background: #00ff88;
  color: #0a0e27;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 5px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  font-family: 'Courier New', monospace;
  margin-top: 1rem;
}

.btn-save:hover {
  transform: scale(1.05);
  box-shadow: 0 5px 15px rgba(0, 255, 136, 0.4);
}

.summary-panel {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  border-radius: 10px;
  padding: 1.5rem;
}

.summary-panel h2 {
  color: #00b4d8;
  margin-top: 0;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.summary-item {
  background: rgba(0, 0, 0, 0.3);
  padding: 1.5rem;
  border-radius: 8px;
  border-left: 4px solid #00ff88;
}

.summary-item h4 {
  color: #00ff88;
  margin-top: 0;
}

.summary-item ul {
  list-style: none;
  padding: 0;
}

.summary-item li {
  padding: 0.5rem 0;
  color: #ffffff;
  border-bottom: 1px solid rgba(0, 255, 136, 0.1);
}

.summary-item li:last-child {
  border-bottom: none;
}

.summary-item strong {
  color: #00b4d8;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the scoped attribute do in <style>?

  2. 2. How do you style child components in scoped styles?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Add scoped styles to MarsPanel.vue with classes for the panel (.panel), title (.title), and status (.status).

  • Click in order

    Arrange the elements of a scoped style declaration:

  • Vertical ordering

    Arrange the steps for creating a component from start to use:

  1. QuestionThe scoped attribute in style
  2. QuestionDeep selectors in scoped styles
  3. Coding taskPractice: Scoped styles
  4. Click in orderScoped style declaration
  5. QuestionEnabling CSS Modules
  6. Put in orderCreating a complete component

Useful articles