浅谈 CSS 关键字 initial、inherit 和 unset

经常会碰到,问一个 CSS 属性,例如 position 有多少取值。

通常的回答是 staticrelativeabsolutefixed 。当然,还有一个极少人了解的 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:

image

可继承属性

最后罗列一下默认为 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题目(四)-- 从倒影说起,谈谈 CSS 继承 inherit,合理的运用 inherit 可以让我们的 CSS 代码更加符合 DRY(Don‘’t Repeat Yourself )原则。

unset

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

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

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

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

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

使用 unset 继承/取消样式:

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

子级元素一
子级元素二
.father { color: red; border: 1px solid black; } .children { color: green; border: 1px 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 定位元素。

image

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

假设样式结构如下:

fixed-left
fixed-right

通常而言,样式如下:

.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;
}

CodePen Demo -- unset Demo;

推荐 参考文档

你可能感兴趣的:(浅谈 CSS 关键字 initial、inherit 和 unset)