css 作用域是全局的,项目越来越大,人越来越多,命名慢慢成为问题,以下是几种解决命名问题的方案

一. BEM

以 .block__element--modifier 形式命名,命名有含义,block 可视为模块,有一定作用域含义

实例

.dropdown-menu__item--active

二. scoped css

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

目标:当前组件样式不会影响其它组件

给组件的 dom 节点添加惟一属性,并转换 style 标签中的 css 匹配该属性,使得 css 作用域有限

实例

<style scoped>.example {  color: red;}</style> <template>  <div class="example">hi</div></template>

转换结果:

<style>.example[data-v-f3f3eg9] {  color: red;}</style> <template>  <div class="example" data-v-f3f3eg9>hi</div></template>

三. css modules

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

将 css 的选择器转换成惟一的字符串,运用到 dom。是在用算法命名,记录了人的命名到算法命名的 map 表

实例

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

转换结果:

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

四. css-in-js

参考:github.com/styled-comp…

将 css 内容用惟一的选择器表示。同 css modules,用算法命名。将 css 视为 js 的字符串,赋予 css 更多能力

实例

<template>  <css-in-js></css-in-js></template> <script>  import styled from vue-styled-components;  export default {    components: {      cssInJs: styled.div `                color: red;            `    }  }</script>

转换结果:

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

五. 总结

BEM 让命名有规律、有含义,block 可视为模块,有一定作用域含义 scoped css 限定 css 作用域,无关命名。无法适配多套主题 css modules 使用算法命名,没有了命名冲突,也限定了 css 作用域。无法适配多套主题 css-in-js 使用算法命名,拥有 css modules 的优势。同时将 css 视为 js 的字符串,赋予 css 更多能力

到此这篇关于css 命名:BEM, scoped css, css modules 与 css-in-js的文章就介绍到这了,更多相关css 命名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!

css 命名:BEM, scoped css, css modules 与 css in js详解