经常会碰到,问一个 CSS 属性,例如position有多少取值。
通常的回答是static、relative、absolute和fixed。当然,还有一个极少人了解的sticky。其实,除此之外, CSS 属性通常还可以设置下面几个值:
initial
inherit
unset
revert1 2 3 4 5 6 7 8{ 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题目(四)-- 从倒影说起,谈谈 CSS 继承 inherit,合理的运用 inherit 可以让我们的 CSS 代码更加符合 DRY(Don‘’t Repeat Yourself )原则。
unset
名如其意,unset关键字我们可以简单理解为不设置。其实,它是关键字initial和inherit的组合。
什么意思呢?也就是当我们给一个 CSS 属性设置了unset的话:
如果该属性是默认继承属性,该值等同于inherit
如果该属性是非继承属性,该值等同于initial
举个例子,根据上面列举的 CSS 中默认继承父级样式的属性,选取一个,再选取一个不可继承样式:
选取一个可继承样式:color
选取一个不可继承样式:border
使用unset继承/取消样式:
看看下面这个简单的结构:
1 2 3 4子级元素一
1 2 3 4 5 6 7 8 9 10 11 12 13 14.father { color:red; border:1pxsolidblack; } .children { color:green; border:1pxsolidblue; } .unset { color: unset; border: unset; }
由于color是可继承样式,设置了color: unset的元素,最终表现为了父级的颜色red。
由于border是不可继承样式,设置了border: unset的元素,最终表现为border: initial,也就是默认 border 样式,无边框。
CodePen Demo -- unset Demo;
unset的一些妙用
例如下面这种情况,在我们的页面上有两个结构类似的position: fixed定位元素。
区别是其中一个是top:0; left: 0;,另一个是top:0; right: 0;。其他样式相同。
假设样式结构如下:
1 2 3 4fixed-left fixed-right
通常而言,样式如下:
1 2 3 4 5 6 7 8 9 10 11 12.left, .right{ position:fixed; top:0; ... } .left{ left:0; } .right{ right:0; }
使用 unset 的方法:
1 2 3 4 5 6 7 8 9 10 11.left, .right{ position:fixed; top:0; left:0; ... } .right{ left: unset; right:0; }
CodePen Demo -- unset Demo;