CSS
Dynamic Styling with Vue 3 `v-bind()` in CSS
Explore how to dynamically bind JavaScript reactive variables directly into your Vue 3 component's CSS `<style>` blocks for responsive styling.
<template>
<div class="dynamic-box">
<p>This box has dynamic styling!</p>
<button @click="toggleColor">Toggle Color</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const dynamicColor = ref('blue');
const boxSize = ref('100px');
const toggleColor = () => {
dynamicColor.value = dynamicColor.value === 'blue' ? 'red' : 'blue';
boxSize.value = boxSize.value === '100px' ? '150px' : '100px';
};
</script>
<style scoped>
.dynamic-box {
background-color: v-bind(dynamicColor); /* Bind reactive variable */
width: v-bind(boxSize);
height: v-bind(boxSize);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: white;
font-weight: bold;
border-radius: 8px;
transition: all 0.3s ease;
}
button {
margin-top: 10px;
padding: 8px 15px;
background-color: white;
color: v-bind(dynamicColor);
border: 1px solid v-bind(dynamicColor);
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease, color 0.3s ease;
}
button:hover {
background-color: v-bind(dynamicColor);
color: white;
}
</style>
How it works: Vue 3 allows you to use `v-bind()` directly within your component's `<style>` block to inject reactive JavaScript variables into CSS properties. This powerful feature enables dynamic styling based on component state without manually manipulating inline styles or generating complex CSS classes. Whenever `dynamicColor` or `boxSize` changes, the bound CSS properties automatically update, providing a seamless reactive styling experience.