[Vuejs]-How to dynamically apply CSS in vue.js?

2👍

Load different CSS while user click the button similar to this . Codepen : https://codepen.io/anon/pen/NJEoVM

HTML

    <div id="app" :class="size">
  <div class="text">Text</div>
  <input class="ipt"/><br/><br/> 
  <button class="btn" @click="change('small')">Small</button>
  <button class="btn"  @click="change('medium')">Medium</button>
  <button class="btn"  @click="change('large')">Large</button>
</div>

CSS

    .small .ipt{
  width: 100px;
  height:30px;
}
.small .text{
  font-size: 18px;
}

.medium .ipt{
  width: 300px;
  height:50px;
}
.medium .text{
  font-size: 32px;
}

.large .ipt{
  width: 600px;
  height:100px;
}
.large .text{
  font-size: 64px;
}

Javascript

    new Vue({
  el: '#app',
  data:()=>({
  size:'small'
}),
methods:{
  change(val){
    this.size = val
  }
}
});

1👍

Actually, you can make use of Custom Properties aka CSS variables.

Firstly, define the button CSS styles

   /* button.css */
   #buttonRef {
     --fontSize: 16px;
     font-size: var(--fontSize)
    }

The overall flow would be something like the following one e.g

methods: {
  changeButtonSize: function(size, event) {
    event.preventDefault();

    /* size might be either of 's', 'm', 'l' */

    /* let the button ref is stored in refs */

    const buttonRef = this.$refs[“buttonRef”];

    let fontSize = 16;

    switch(size) {
      case 's':
        fontSize = 12;
      case 'm':
        fontSize = 18;
      case 'l':
        fontSize = 22;
    }

    /* dynamically change the value for custom property */
    buttonRef.style.setProperty("--fontSize", fontSize);

  }
}

0👍

you can set up 3 classes:

.small {font-size:12px}
.medium {font-size:18px}
.large {font-size:24px}

Then add or remove them to your main parent div onClick.

If you have discreetly set the font-size on the elements, you’ll have to target those elements as such:

.small .description { font-size:12px }
.small .title{ font-size:16px }
👤4ndy

Leave a comment