We use cookies to enhance your experience on the site
CodeWorlds

Scoped Styles and CSS Modules

Style isolation in components - like gilding only a selected part of a sculpture.

Scoped Styles

1<template>
2  <div class="card">
3    <h3 class="title">{{ title }}</h3>
4  </div>
5</template>
6
7<style scoped>
8/* Only for this component */
9.card {
10  border: 1px solid #ccc;
11  padding: 1rem;
12}
13
14.title {
15  color: #333;
16}
17
18/* Deep selector - affect child components */
19.card :deep(.child-class) {
20  color: blue;
21}
22
23/* Slotted content */
24:slotted(.slot-class) {
25  font-weight: bold;
26}
27
28/* Global in scoped */
29:global(.global-class) {
30  background: yellow;
31}
32</style>

CSS Modules

1<template>
2  <div :class="$style.card">
3    <h3 :class="$style.title">{{ title }}</h3>
4    <p :class="[$style.text, $style.highlighted]">Description</p>
5  </div>
6</template>
7
8<style module>
9.card {
10  border: 1px solid #ccc;
11}
12
13.title {
14  color: #333;
15}
16
17.text {
18  font-size: 14px;
19}
20
21.highlighted {
22  background: yellow;
23}
24</style>
25
26<script setup>
27import { useCssModule } from 'vue'
28
29const styles = useCssModule()
30console.log(styles.card) // "Card_card_1a2b3c"
31</script>

Dynamic Styles

1<template>
2  <div
3    class="card"
4    :style="{
5      '--primary-color': primaryColor,
6      '--border-width': borderWidth + 'px'
7    }"
8  >
9    <h3>{{ title }}</h3>
10  </div>
11</template>
12
13<script setup>
14import { ref } from 'vue'
15
16const primaryColor = ref('#8b7355')
17const borderWidth = ref(2)
18</script>
19
20<style scoped>
21.card {
22  border: var(--border-width) solid var(--primary-color);
23  color: var(--primary-color);
24}
25</style>

v-bind() in CSS

1<template>
2  <div class="card">
3    <input v-model="color" type="color" />
4    <p>This text changes color!</p>
5  </div>
6</template>
7
8<script setup>
9import { ref } from 'vue'
10
11const color = ref('#8b7355')
12</script>
13
14<style scoped>
15p {
16  /* Reactive binding! */
17  color: v-bind(color);
18}
19</style>
Go to CodeWorlds