Styles from Data

Sometimes a value from data goes straight into CSS: the width of a bar, a color that the user picked, a size. For that, there's :style, with an object of CSS properties:

<script setup>
const size = 24;
const color = "#8b5e34";
</script>

<template>
    <p :style="{ fontSize: size + 'px', color: color }">Corner Café</p>
</template>

The paragraph's text is 24 pixels big and brown.

The names of CSS properties are written in camelCase, as with element.style in the JavaScript course: fontSize for font-size, backgroundColor for background-color. (The names from CSS work too, in quotes: { 'font-size': size + 'px' }.) A value is text, with its unit, as in CSS: size + 'px' gives 24px. With just a number, { fontSize: size }, the browser gets 24 without a unit and ignores it.

Use :style for values that come from data. For looks that are always the same, or that only switch on and off, a class in <style scoped> with :class is easier to read.

Instructions

  1. Give the card its background color from the variable cardColor: bind its style to { backgroundColor: cardColor }.

  2. Make the green part of the bar as wide as the stamps collected. Each stamp is a tenth of the bar, so bind the style of .filled to { width: stamps * 10 + '%' }. Click Add a stamp a few times.