CSS scopes are global. As projects get bigger and people get bigger, naming becomes a problem. Here are a few ways to solve naming problems

The BEM.

Block__element — named in the form of the modifier, the name has meaning, block can be regarded as a module, has a certain scope meaning

The instance

.dropdown-menu__item–active

2. Scoped CSS

Reference: vue-loader.vuejs.org/zh/guide/sc…

Goal: The current component style does not affect other components

Adding a unique property to the component’s DOM node and converting the CSS in the style tag to match that property makes the CSS scoped

The instance

<style scoped>
.example {
  color: red;
}
</style>

<template>
  <div class="example">hi</div>
</template>
Copy the code

Conversion result:

<style>
.example[data-v-f3f3eg9] {
  color: red;
}
</style>

<template>
  <div class="example" data-v-f3f3eg9>hi</div>
</template>
Copy the code

3. CSS modules

Reference: vue-loader.vuejs.org/zh/guide/cs…

Convert CSS selectors into unique strings and apply them to the DOM. Algorithmic naming records the names of people to the algorithmic named map table

The instance

<style module>
.red {
  color: red;
}
</style>
<template>
  <p :class="$style.red">
    This should be red
  </p>
</template>
Copy the code

Conversion result:

<style module>
._1yZGjg0pYkMbaHPr4wT6P__1 {
  color: red;
}
</style>
<template>
  <p class="_1yZGjg0pYkMbaHPr4wT6P__1">
    This should be red
  </p>
</template>
Copy the code

4. CSS – in – js

Reference: github.com/styled-comp…

Represent CSS content with a unique selector. Same as CSS modules, named algorithmically. Think of CSS as js strings, giving CSS more power

The instance

<template>
  <css-in-js></css-in-js>
</template>

<script>
  import styled from 'vue-styled-components';
  export default {
    components: {
      cssInJs: styled.div ` color: red; `}}</script>
Copy the code

Conversion result:

<template>
    <div class="gXTzCp"></div>
</template>
<style>
.gXTzCp {
    color: red;
}
</style>
Copy the code

In live.

  1. BEM makes naming regular and meaningful, and blocks can be treated as modules with scoped meaning
  2. Scoped CSS Scoped CSS, independent of naming. Does not fit multiple themes
  3. CSS modules use algorithmic naming, which eliminates naming conflicts and limits the CSS scope. Does not fit multiple themes
  4. Css-in-js uses algorithmic naming and has the advantage of CSS modules. At the same time, CSS is treated as a STRING of JS, giving CSS more power