css自定义属性

css自定义属性分为全局定义属性和局部定义属性。

一:全局

  1.定义:

  :root{    //此处的root是固定的。

    --them-color:blue;    //自定义属性时以--开头,告诉浏览器这是自定义的。

  }

  2.使用:

  <style type="text/css">

    .div{  

      background-color:var(--them-color);    

       //如果自定义的属性出不来或其他问题,可在之后写属性值。例如:background-color:var(--them-color,blue);

        也可写另一个属性名:background-color:var(--them-color,var(--them-color1));

      }

  </style>

  <div class="div">111</div>

二:局部

  1:定义

  .foo{

    --them-color:yellow;

  }

 .div{

  color:var(--them-color);

  }

  2:使用:

  <div class="foo div">121321</div>  //此处的foo相当于一个基类,目的是存取所有的属性值,他的子元素从这个库里取属性。

 

例子:

<style type="text/css">
.foo{
--them:yellow;
--width-outer:800px;
--height-outer:400px;
--width-inner:100px;
--height-inner:100px;
--bg-inner1:red;
--bg-inner2:orange;
--bg-inner3:purple;
}
.div{
width: var(--width-outer);
height: var(--height-outer);
border:1px solid var(--them);
margin: 20px auto;
}
.foo div:nth-child(1){
width: var(--width-inner);
height: var(--height-inner);
background-color: var(--bg-inner1);
}
.foo div:nth-child(2){
width: var(--width-inner);
height: var(--height-inner);
background-color: var(--bg-inner2);
}
.foo div:nth-child(3){
width: var(--width-inner);
height: var(--height-inner);
background-color: var(--bg-inner3);
}

</style>

 <body>  

<div class="div">
<div></div>
<div></div>
<div></div>
</div>

</body>

 

四:总结

在一个组件里或者全局将经常使用的属性提取出来,比如主题色,用的时候直接使用变量。便于维护代码,改的时候直接改一处即可。

posted @ 2017-06-28 11:25  王玮-web  阅读(1033)  评论(0编辑  收藏  举报