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
EasyCreate 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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks