css奇技淫巧(一、减少重复的代码)

引言:
有可能你会在你的css布局中这么写:

.text{
    font-size: 20px;
    line-height: 20px;
    color: #ffffff;
    background: #3397ff;
    margin-top: 40px;
    width: 200px;
    border: 1px solid #3397ff;
 }
<div class="box">
    <p class="text">css3 奇技淫巧</p>
</div>

这种情况要是 font-size 改变,将会顺带需要改动几处代码,line-heightmargin-topwidth

1、使用rem或em

em 是相对于父元素的font-size 做出改变的

    .box{
        font-size: 20px;
    }
    .text{
        font-size: 1em;
        line-height: 1em;
        color: #ffffff;
        background: #3397ff;
        margin-top: 2em;
        width: 20em;
        border: 1px solid #3397ff;
    }

rem是相对于html的font-size 做出改变的

    body,html {
        font-size: 20px;
    }
    .text{
        font-size: 1em;
        line-height: 1em;
        color: #ffffff;
        background: #3397ff;
        margin-top: 2em;
        width: 20em;
        border: 1px solid #3397ff;
    }

2、使用 currentColor

currentColor 可以说是css的一个变量,会被解析为 clolor 的一个值,所以下面我们就可以给跟
color同样值使用currentColor,来减少以后代码变动改动的地方:

    .text{
        color: #3397ff;
        border: 1px solid currentColor;
    }

3、使用 inherit

inherit继承的意思,它会继承来着父元素的对应值

    .box{
        font-size: 20px;
        color: #3397ff;
        background: #333333;
        border: 1px solid currentColor;
    }
    .text{
        line-height: 2em;
        margin-top: 2em;
        width: 20em;
        color:inherit;
        background:inherit;
        border:inherit;
    }

4、使用预处理器

    @mixin borderRadius($radius) {
        -webkit-border-radius: $radius;
        -moz-border-radius: $radius;
        -ms-border-radius: $radius;
        -o-border-radius: $radius;
        border-radius: $radius;
    }
    原文作者:曾田生z
    原文地址: https://segmentfault.com/a/1190000010245885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞