css变量

120 阅读1分钟

:root和var()

:root是一个伪类,表示文档根元素,相当于html选择器,但是css权重比html选择器要高。

下面的案例中,最终的背景色是blue

:root {
  background-color: blue;
}

html {
  background-color: yellow;
}

在root中声明相当于定义全局属性,可以使用var()*用属性

:root {
    --color: red;
}

.box {
    width: 200px;
    height: 200px;
    background-color: var(--color);
}

var()引用的变量具有就近原则,会使用最近一层祖先节点中定义的变量

下面的例子中,box1背景色是pink,box2背景色是red

<style>
    body {
      --color: red;
    }

    .box {
      width: 200px;
      height: 200px;
      --color: pink;
    }

    .box1 {
      width: 20px;
      height: 20px;
      background-color: var(--color);
    }

    .box2 {
      width: 20px;
      height: 20px;
      background-color: var(--color);
    }
</style>

<body>
  <div class="box">
    <div class="box1">
    </div>
  </div>
  <div class="box2"></div>
</body>

css变量在vue中的使用

问题背景:基于element-ui的upload组件封装了一个图片上传组件imageUpload,想通过父组件prop中传递的width和height来动态决定imageUpload的宽高。直接修改upload组件最外层dom元素的宽高不可行,必须修改封装在upload组件里的某些dom元素。

vue2

给el-upload设置class并传入js变量作为style,组件内部的元素引用变量(使用计算属性,当data数据发生改变时,style也会同步发生改变)

<template>
	<el-upload
      class="image-upload"
      :style="CSSVars"
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
</template>

<script>
    props: ['width', 'height']
    computed: {
        CSSVars() {
            return {
              '--width': this.width,
              '--height': this.height,
            };
        }
    }
</script>

<style>
    .image-upload {

      .el-upload--picture-card {
        width: var(--width);
        height: var(--height);
        line-height: var(--height);
      }

      .el-upload-list--picture-card {
        line-height: 0px;
        font-size: 0px;

        .el-upload-list__item {
          width: var(--width);
          height: var(--height);
          margin-right: 15px;
          margin-bottom: 0;
        }
      }
    }
</style>
vue3

vue3提供了一种更快捷的方法:vars绑定

<template>
	<el-upload
      class="image-upload"
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
</template>

<script>
    props: ['width', 'height']
</script>

<style vars="{width, height}">
    .image-upload {

      .el-upload--picture-card {
        width: var(--width);
        height: var(--height);
        line-height: var(--height);
      }

      .el-upload-list--picture-card {
        line-height: 0px;
        font-size: 0px;

        .el-upload-list__item {
          width: var(--width);
          height: var(--height);
          margin-right: 15px;
          margin-bottom: 0;
        }
      }
    }
</style>