點燈坊

失くすものさえない今が強くなるチャンスよ

Style Binding for CSS

Sam Xiao's Avatar 2021-11-25

We can bind data to CSS inline style by style binding.

Version

Vue 2.6.11

Object

style000

Hello World is red, which is binding by data, not directly written by inline style.

<template>
  <div :style="{ color }">Hello World</div>
</template>

<script>
export default {
  data: _ => ({
    color: 'red'
  }),
}
</script>

Line 2

<div :style="{ color }">Hello World</div>
  • Use :style to bind Object to style attribute
  • We can use ES6 Object Shorthand to minimize Object

Line 7

data: _ => ({
  color: 'red'
}),

Define color property for style binding.

<template>
  <div :style="red">Hello World</div>
</template>

<script>
export default {
  data: _ => ({
    red: {
      color: 'red'
    }
  }),
}
</script>

Line 2

<div :style="red">Hello World</div>

We can also bind Object to style attribute directly.

Line 7

data: _ => ({
  red: {
    color: 'red'
  }
})

Define red Object for style binding.

Array

style001

Hello World is not just red; its font size is bigger.

<template>
  <div :style="[red, lg]">Hello World</div>
</template>

<script>
export default {
  data: _ => ({
    red: {
      color: 'red'
    },
    lg: {
      fontSize: '30px'
    }
  }),
}
</script>

Line 2

<div :style="[red, lg]">Hello World</div>

We can bind multiple Objects to style attributes; just collect these Objects in Array.

Line 7

data: _ => ({
  red: {
    color: 'red'
  },
  lg: {
    fontSize: '30px'
  }
}),

Define multiple Objects for style binding.

Conclusion

  • If we want to change CSS style at runtime, we can use style binding by JavaScript

Reference

Vue, Binding Inline Styles