青青子衿,悠悠我心。但为君故,沉吟至今。

css 中的 initial inherit unset 意思

写css时,在对属性进行选值,经常遇到unset , initial,inherit三个值。这几个值的含义。

  • 1.inherit 可继承性

    继承的意思。

    每一个 CSS 属性都有一个特性就是,这个属性必然是默认继承的 (inherited: Yes) 或者是默认不继承的 (inherited: no)其中之一,我们可以在 MDN 上通过这个索引查找,判断一个属性的是否继承特性。

    譬如,以 background-color 为例,由下图所示,表明它并不会继承父元素的 background-color:

    可继承属性

    最后罗列一下默认为 inherited: Yes 的属性:

    • 所有元素可继承:visibility 和 cursor
    • 内联元素可继承:letter-spacing、word-spacing、white-space、line-height、color、font、 font-family、font-size、font-style、font-variant、font-weight、text- decoration、text-transform、direction
    • 块状元素可继承:text-indent和text-align
    • 列表元素可继承:list-style、list-style-type、list-style-position、list-style-image
    • 表格元素可继承:border-collapse

    还有一些 inherit 的妙用,合理的运用 inherit 可以让我们的 CSS 代码更加符合 DRY(Don‘’t Repeat Yourself )原则。

  • 2.initial 默认值
     
    关键字用于设置 CSS 属性为它的默认值,可作用于任何 CSS 样式。(IE 不支持该关键字)

  • unset  无设置(不设置)

    名如其意,unset 关键字我们可以简单理解为不设置。其实,它是关键字 initial 和 inherit 的组合。

    什么意思呢?也就是当我们给一个 CSS 属性设置了 unset 的话:

    1. 如果该属性是默认继承属性,该值等同于 inherit
    2. 如果该属性是非继承属性,该值等同于 initial

    举个例子,先列举一些 CSS 中默认继承父级样式的属性:

    • 部分可继承样式: font-sizefont-familycolortext-indent
    • 部分不可继承样式: borderpaddingmarginwidthheight

     

    使用 unset 继承父级样式:

    看看下面这个简单的结构:

    1
    2
    3
    4
    <div class="father">
        <div class="children">子级元素一</div>
        <div class="children unset">子级元素二</div>
    </div>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    .father {
        colorred;
        border1px solid black;
    }
     
    .children {
        colorgreen;
        border1px solid blue;
    }
     
    .unset {
        color: unset;
        border: unset;
    }
    1. 由于 color 是可继承样式,设置了 color: unset 的元素,最终表现为了父级的颜色 red

    2. 由于 border 是不可继承样式,设置了 border: unset 的元素,最终表现为 border: initial ,也就是默认 border 样式,无边框。

    CodePen Demo -- unset Demo;

     

     

    unset 的一些妙用

    例如下面这种情况,在我们的页面上有两个结构类似的 position: fixed 定位元素。

     

    区别是其中一个是 top:0; left: 0;,另一个是 top:0; right: 0;。其他样式相同。

    假设样式结构如下:

    1
    2
    3
    4
    <div class="container">
        <div class="left">fixed-left</div>
        <div class="right">fixed-right</div>
    </div>

    通常而言,样式如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    .left,
    .right {
        positionfixed;
        top0;   
        ...
    }
    .left {
        left0;
    }
    .right {
        right0;
    }

    使用 unset 的方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    .left,
    .right {
        positionfixed;
        top0;   
        left0;
        ...
    }
    .right {
        left: unset;
        right0;
    }

    CodePen Demo -- unset Demo;

     

posted @ 2018-08-11 17:06  revres  阅读(481)  评论(0编辑  收藏  举报

乐观加坚持