Menu
CoddyTech

Dynamic Styles

Part of the Fundamentals section of Coddy's Vue journey. Lesson 13 of 55.

A style binding can derive CSS values from state. This example renders a bar 30px wide. Increasing length to 45 updates the width without replacing the element.

const length = ref(30);
// <div :style="{ width: length + 'px' }">Bar</div>

The style object uses JavaScript property names, such as backgroundColor. CSS lengths still need units when the property requires them. Store a number when you want arithmetic, then add a unit at the boundary where the value becomes CSS.

challenge icon

Challenge

Easy

Create a progress bar div#result starting 40px wide. Bind its width to a number ref plus the px unit. Button #grow adds 15 to the width.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals