How to Deal With CSS/SCSS in VueJs

Mon Apr 23 2018

Paul Shan

CSS are very helpful in order to make the HTML templates look more alive. In the previous article we have learned how to write our first code ‘Hello World!’ in vueJs and today we will show how to style it in vueJs using CSS.
Data binding is a common practice in vue for manipulating the class of a DOM element. Our today’s topic will cover all the processes of binding CSS to an HTML element using Vue.js.
As we know, There are two different ways of adding CSS in HTML. The first one is using the style attribute and the second one is using class. The second approach is more preferable in real life projects but we will discuss both of them.

A bit on v-bind

Let’s recall this topic in a minute. The v-bind: directive gets used to bind data and reactively update the DOM. We can use the : (colon) only as the shorthand of v-bind:. In this article, we will be mainly using v-bind:class and v-bind:style directives to achieve the desired results.

v-bind:class

Lets say, this is our .vue file and we want to add CSS to the <h1> element.

Hello World!





  export  default {
    name:'App',
    data (){
      return{
      
      }
    }
  }





To add CSS we can either use the v-bind:class directive or the v-bind:style directive. Starting with the first one.

Classes are more preferable and acceptable way of styling an HTML content. It reduces the clumsiness and helps us code in an organized way. One can choose between three techniques of binding classes to an element in VueJs.

  • Using the class name.
  • Passing object directly.
  • Use an object from the component.

Using the class name

This one is comparatively a simple approach. We will define our class inside the <style> tag in the .vue file.


  
    .headingColor{
      color:yellow;
    }
  

Next we will define the class name as the value of a object property in the data() function.


  data (){
    return{
      headingColor:'headingColor'
    }
  }

Now bind this property to the element.

Hello World!




That’s it. The ‘Hello World!’ will be printed in yellow color.

Passing objects directly

In order to dynamically toggle a class we can pass an object to v-bind:class. This approach helps us dynamically add or remove a class from an element. Here is how you can do it.

Hello World!


  

The headingColor is the name of the actual class and the presence of this class will be determined by the truthfulness of its associate value.


data (){
  return{
    activeStatus:  true
  }
} 

In our case this class will be applied to the element as activeStatus is true.

We can bind multiple classes too.

Hello World!



Use an object from the component

If you do not want to bind the objects inline, you may try the below approach.



  data (){
    return{
      activeStatus: {
        headingColor:  true,
        bgColor:  false
      }
    }
  }

The activeStatus object holds the truthfulness of the CSS classes.

Hello World!


  

And we are binding this object to v-bind:class.

Multiple

In order to bind multiple data properties we pass them in an array.
<h1 v-bind:class="[headingColor,bgColor]"> Hello World! </h1>

v-bind:style

There are three approaches you can follow. All of them will direct you to the same result.

  • Directly passing an object.
  • Use an object from the component.
  • Passing an array.

Directly Passing An Object

In this case, we will directly pass an object to the directive. Follow the syntax below.
<h1 v-bind:style="{ }"> Hello World! </h1>
The properties of this object will be the name of the actual CSS property and the values will be as defined in the data() function. This is how it will work:


  data (){
    return{
      headingColor: 'red'      
    }
  }

Here we have returned an object whose property name is headingColor and the value is a string, ‘red’.

Hello World!


  

Make sure you are using camelCase instead of kebab-case. The CSS property background-color will be written as backgroundColor.

Use an object from the component

Here instead of defining the object inside the template’s element, we will define it inside the data() function



  export  default {
    name:'App',
    data (){
      return{
        headingColor:{
          color:'pink'
        }
      }
    }
  }

and will pass the object name accordingly.

Hello World!


  

A better approach than the previous one.

Multiple (By passing an array)

What is you want to bind multiple data objects? We will simply pass them in an array. Follow the code below.


  data (){
    return{
      headingColor:{
        color:'red'
      },
      bgColor:{
        backgroundColor:  'black'
      }
    }
  }

Now here is how you will bind the objects.

Hello World!


  

These are the possible ways of using the v-bind:style directives.

Inserting Multiple Values

It is possible that a browser didn’t support our given CSS style. Suppose we are using the font Coalition which is not supported by a certain browser, to handle such cases, we can provide multiple values using an array. So in case, our given primary value is unsupported by a browser, the alternative value too will be of our choice not the browser’s.
<div v-bind:style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
The last value of the array supported by the browser will be rendered.

Scoped CSS

When a <style> tag contains the scoped attribute, it only applies the CSS to the associate elements of its own component.
The scoped attribute is important while importing components else the CSS of the imported component may override the CSS of the present component. Suppose this is the CSS of our root component (App.vue),


  
    h1 {
      color:pink
    }
  

In this component the <h1> element’s text color should be pink. But if we import here another component having no scoped, it will over ride the CSS of App.vue. Take a look at our Message.vue component below that has been imported to the App.vue.


  
    h1{
      color:green
    }
  

Now, both App.vue and Message.vue’s <h1> element’s content color will become green which is not desirable. To solve this issue we will use scoped attribute which will make the CSS of a component applicable to its own element only.


  
  h1{
    color:green
  }
  

Here is how you should do it to get the separate CSS <h1> text color for separate components.

In case, you want a bunch of CSS to bescoped, not all the CSS available in a component. To do so use multiple <style> tags.

 
    
     /* global styles */ 
   
   
   
      /* local styles */ 
  

SCSS and other css preprocessors

Till now we have learned how to style in vueJs using style and class. Among these two the class approach is more preferable. But going with the old school may sometimes make life painful and tedious. And that’s the reason we use SCSS (or SASS) in our projects.
So, lets see how SCSS works and how to deal with SCSS in vueJs.

How to configure SCSS in vue-cli project

First of all you need the appropriate loaders in your project. So let’s install sass-loader.

npm install sass-loader

Once the package installation is done, you need to add it in your webpack rules. You can check build/webpack.base.conf.js and add the rule like the following. I am not installing css-loader separately cause vue cli already installs it. In case it is not there in your project, feel free to run npm install css-loader.

{
  test: /\.(scss|css)$/,
  loader: ['css-loader', 'sass-loader'],
}

Working with SCSS in vue-cli

To use SCSS, add lang attribute to the <style> tag in your .vue files. Now you can write your css preprocessor code in the style tag.


  

  

Here is an example code:

Hello World!


  
  
  
    export default {
      name:'App',
      data (){
        return{
          headingColor:'headingColor'
        }
      }
    }
  
  
  
    $primaryColor: green; //declaring variable
    
    .headingColor {
      color: $primaryColor;
    }
  
  

Conclusion

Hopefully our this article will help increasing your flexibility with VueJs styling. Let us know in the comment section if you have any query regarding this, we will surely get back to you. Stay tuned for more upcoming articles on Vue. Happy Coding!

SHARE THIS ARTICLE

post-thumbnail
Today everyone knows the importance of a lightning-fast website and how the speed impacts the conversion rate of a business. Today, everyone wants the site to be a PWA so that the mobile users can have an app-like experience with the website because, for the majority of the merchants, the customers come through mobile devices.
Tue Apr 20 2021
post-thumbnail
Here we are going to see how you can manage backup and restore of Postgres database with docker.
Thu Sep 03 2020
post-thumbnail
Image sliders or carousels always have increased the UI attraction of websites and they are pretty useful for reflecting the major roles/products too. In case, I am having a website that sells tee-shirts,
Mon Apr 30 2018

About VoidCanvas

This blog was created out of hobby and talks mostly about technology, web development, JavaScript, NodeJS and related topics. Thank you for reading my blog.

Copyright 2022 - www.voidcanvas.com

Popular Articles

Authentication using Google's oAuth api with node.js

Thu Mar 10 2016

OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application.

CSS3 Loader Snippet Collection: (Part 2 - Squares)

Sat Mar 01 2014

This is a continuation of my CSS3 loader snippet collection series. I've provided spinning css3 animation loader in the part 1 of this series and here in part 2, I'm providing various square type loading