· css vue

Right Way to Use CSS Varialbes in Vue, Inspired by Tailwind.css

I can never emphasise enough on how Vue makes my life easy but I definitely want to work more in Vue if I’m doing frontend development. One issue that I face when building Vue applications using single file components(SFC) is about sharing the common style across components. There is no easy way to do this and most of you will be fine doing a copy paste of the styles across the components.

Another cool project that I like is tailwind css. I like the idea of how we can have CSS utility classes and build things fast. If I were to summarize my take away from using this library they would be:

Negetives

Positives

So from here, I know that I want the uniformity aspect of the code but I also want the ability to write idiomatic BEM based class names. So how do we do this?

I started out by extracting the very well defined constants in the tailwind.js file as CSS variables. Now I access these variables throughout the application. To make it work with the view we will need to follow the following steps.

  1. Create a file src/assets/css/constants.css
  2. Copy the content of this gist to the above CSS file.
  3. Import the CSS file like in you main.js file like import '@/assets/css/constants.css'
  4. Now all the variables defined in the constants file are available in all our components. Really neat!

Here is an example of how my styles section of a component will look like:

.movie__header {
  margin: var(--spacing-4);
  color: var(--grey--darker);
}

So now we can use these CSS variables in any component and have our app use standard measures. I hope you like the post. Do let me know your thoughts in the comments. Thanks for reading. :)

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+