谈谈 CSS 关键字 initial、inherit 和 unset

更新日期: 2019-03-09阅读: 2.5k标签: 关键字

经常会碰到,问一个 css 属性,例如 position 有多少取值。 通常的回答是 static、relative、absolute 和 fixed 。当然,还有一个极少人了解的 sticky 。其实,除此之外, CSS 属性通常还可以设置下面几个值:initial inherit unset revert

{
  position: initial;
  position: inherit;
  position: unset

  /* CSS Cascading and Inheritance Level 4 */
  position: revert;
}

了解 CSS 样式的 initial(默认)和 inherit(继承)以及 unset 是熟练使用 CSS 的关键。(当然由于 revert 未列入规范,本文暂且不过多提及。)

 

initial

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

 

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 可以让我们的 CSS 代码更加符合 DRY(Don‘’t Repeat Yourself )原则。

 

unset

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

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

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

举个例子,根据上面列举的 CSS 中默认继承父级样式的属性,选取一个,再选取一个不可继承样式:

  • 选取一个可继承样式: color
  • 选取一个不可继承样式: border

 

使用 unset 继承/取消样式:

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

<div>
    <div>子级元素一</div>
    <div>子级元素二</div>
</div>
.father {
    color: red;
    border: 1px solid black;
}

.children {
    color: green;
    border: 1px solid blue;
}

.unset {
    color: unset;
    border: unset;
}

由于 color 是可继承样式,设置了 color: unset 的元素,最终表现为了父级的颜色 red。

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


unset 的一些妙用

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


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

假设样式结构如下:

<div>
    <div>fixed-left</div>
    <div>fixed-right</div>
</div>

通常而言,样式如下:

.left,
.right {
    position: fixed;
    top: 0;    
    ...
}
.left {
    left: 0;
}
.right {
    right: 0;
}

使用 unset 的方法:

.left,
.right {
    position: fixed;
    top: 0;    
    left: 0;
    ...
}
.right {
    left: unset;
    right: 0;
}

来自:https://www.cnblogs.com/lonelyxmas/p/10495342.html  


链接: https://www.fly63.com/article/detial/2287

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!