Search code examples
javascripthtmlcssvuejs2vue-loader

Vue js loader override global css


I want to override the global css with the css defined in vue-loader component.

Currently I have this in index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard</title>
    <link rel="stylesheet" href="build/styles.css">
</head>
<body id="the-dashboard">
<div id="app">

</div>


//......  Other Code Goes Here ......//
</body>
</html>

And in my vue component I have a scoped style:

<template>
  // ..... Some Code Here ..... //
</template>

<style scoped>
   // ... css code here ... //
</style>
<script>
   // ... script goes here ... //
</script>

What I want is that when this component is loaded, it should totally override the global css in index.html. Which is to say that it should behave in such a way that only scoped css should be the one that should apply to the whole body(the css imported in index.html should not at all be used).

Is that possible?


Solution

  • No, it's not possible.

    You can wrap all global styles in some selector, then refactor your HTML to your component don't be inside it.

    .global {
      .someClass {
         ...
      }
    
      .another {
    
      }
    }
    
    <div class="global">
       <div class="someClass">
       ...
    </div>
    
    <component>
       <div class="someClass">
       ...
    </component>
    

    Or maybe you can try too to create an 'global' component, then inside it import the CSS using Sass @import, and it will be included inline. Then you put the tag as scoped (I'm not sure if this will work for children components inside it). That is:

    <style scoped>
      @import 'build/main.css';
    </style>
    

    The best solution actually is: if you don't want that the CSS get global, then don't code it as global. Use classes instead generic tag names and attribute selectors.