CSS variables use in Vue

This won't work as expected because of scoped attribute for stylesheet. Example above compiles into:

[data-v-4cc5a608]:root {
  --var-txt-color: #f00;
}

And, as you understand, it will not target actual :root element.

It can be solved by:

  • Not using scoped attribute for this stylesheet. Notice that it may cause styles conflict with other variables declarations for :root element.

  • Using current component's wrapping element as root. If we declare variables this way:

    .test {
      --var-txt-color: #c1d32f;
      color: var(--var-txt-color);
    }
    
    .test-child-node {
      background-color: var(--var-txt-color);
    }
    

Then it will can reuse variables for other elements of the same component. But still, it won't be possible to use declared variables inside child components without removing scoped, if it is the case.


I know you highlighted "without having to link any stylesheet", but I run into the same issue and there is a simple option - use just one external css file and include it in your App.vue, then you can access the variables anywhere else, in scoped styles as well.

variables.css

:root {
  --font-family: "Roboto", "Helvetica", "Arial", sans-serif;
  --primary-color: #333a4b;
}

App.vue

<style>
  @import './assets/styles/variables.css';
</style>

LandingView.vue

<style scoped>
  #landing-view {
    font-family: var(--font-family);
    font-weight: 300;
    line-height: 1.5em;
    color: var(--primary-color);
  }
</style>