DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Trending

  • AI-Based Threat Detection in Cloud Security
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  1. DZone
  2. Coding
  3. JavaScript
  4. Dynamic Styling in Vue.js

Dynamic Styling in Vue.js

Learn more about different techniques to implement dynamic styling in Vue.js.

By 
Edoardo Cordani user avatar
Edoardo Cordani
·
Oct. 30, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
17.2K Views

Join the DZone community and get the full member experience.

Join For Free

When I started using Vue.js as a front-end framework I immediately enjoyed the easy way I can set up and manage my components. Using single file components let me focus on all aspects regarding the way I build them: I simply need to put 3 tags inside a .vue file and I can start shaping both the visual aspect and all the logic behind the component itself. Talking about styling, the first thing that the official doc tells you is how to style a component: simply insert a style tag (usually at the end of the file) and you're done. 

But when you move on and start to build complex interfaces, you immediately need to perform styling that goes beyond the simple composition of CSS classes. So, during my journey, I discovered several ways to perform dynamic styling, and this article aims to be a short reference for people that come up at first with this need.
In order to show you the different techniques, I'll use a super-simple button component that must use a specific background color value if a boolean prop is true (ok maybe is too simple, but so you'll grasp the concepts quickly).
Let's start with the component code:

HTML
 
<template>
  <button class="my-button">
    {{ text }}
  </button>  
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: ""
    },
    isWarning: {
      type: Boolean,
      default: false
    }
  }
}
</script>

<style lang="scss">
.my-button {
  padding: 10px 20px;
  border-radius: 8px;
  border: 0;
}
</style>

and we call the component like so:

HTML
 
<my-button text="Attention!" :is-warning="true"/>

1 Style Binding

This is the simpler solution, just use Vue.js style binding and change the CSS background-color property:

HTML
 
<template>
  <button 
    class="my-button"
    :style="{'background-color': isWarning ? '#FC4': '#CCC'}"
  >
    {{ text }}
  </button>  
</template>

2 Class Binding

With class binding, we append a specific class only if the prop isWarning is truthy:

HTML
 
<template>
  <button 
    :class="['my-button', {'warning': isWarning}]"
  >
    {{ text }}
  </button>  
</template>

and below in the style tag:

HTML
 
<style lang="scss">
.my-button {
  padding: 10px 20px;
  border-radius: 8px;
  border: 0;
  &.warning {
    background-color: #FC4;
  }
}
</style>

3 Computed Class

With this technique, we simply define a classes the computed value that returns a string of CSS class names based on the component property isWarning value:

JavaScript
 
computed: {
  classes () {
    if (this.isWarning) {
      return 'my-button warning';
    }

    return 'my-button';
  }
}

then we use the class binding we used above, passing only the computed value:

HTML
 
<template>
  <button :class="classes">
    {{ text }}
  </button>
</template> 

4 Computed Style With CSS Variable

Ahh, this is the technique I like the most. It's a variant of the previous one but we use style binding and a CSS variable in order to change the background color.
Let's start using a CSS variable for background-color property:

HTML
 
<style lang="scss">
.my-button {
  padding: 10px 20px;
  border-radius: 8px;
  border: 0;
  background-color: var(--button-bg-color)
}
</style>

then we add a computed value that defines the final value of our --button-bg-color variable:

JavaScript
 
computed: {
  cssVars () {
    return {
      '--button-bg-color': this.isWarning ? '#FC4' : '#CCC'
    }
  }
}

and finally, we add style binding to the button tag:

HTML
 
<template>
  <button 
    class="my-button"
    :style="cssVars"
  >
    {{ text }}
  </button>
</template>

5 Styled-components

Styled-components is a famous CSS-in-JS library used especially by React developers...and you can use it with Vue.js too. You can find the package here, please note that it's compatible only with Vue 2.x.

Install the package (using yarn as the package manager):

 
yarn add vue-styled-components

Due to the simplicity of the component, we define it inside the parent component inside the script tag. First, we must import the library:

JavaScript
 
import styled from 'vue-styled-components';

then we define the component (a styled button) and its property isWarning:

JavaScript
 
const btnProps = {
  isWarning: Boolean
}
const MyButton = styled('button', btnProps)`
  padding: 10px 20px;
  border-radius: 8px;
  border: 0;
  background-color: ${props => props.isWarning ? '#FC4' : '#CCC'};
`;

Note the background-color: ${props => props.isWarning ? '#FC4' : '#CCC'};, here we are telling the library to change the CSS property based on the prop isWarning value.

The last step is to register the newly created component and use it inside the template:

JavaScript
 
....
  components: {
    MyButton
  }
...
HTML
 
<my-button :is-warning="true">
  Attention!
</my-button>

Besides of styled-components library, there are also other CSS-in-JS libraries usable for Vue.js, for example, Emotion through the vue-emotion package.

That's all, hope you find this article useful. If you know other techniques feel free to write me and I'll update the article!

Thanks for reading!

Vue.js HTML

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Creating Scrolling Text With HTML, CSS, and JavaScript
  • Mastering SSR and CSR in Next.js: Building High-Performance Data Visualizations
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!