第一個CSS變數:currentColor

zuo發表於2014-12-02

一、基本介紹

CSS變數正慢慢地從最初的草案到瀏覽器實現。但規範中有個已經存在多年的變數:currentColor。這個CSS特性具有良好的瀏覽器支援和一些實際的應用,本篇文章,我們來學習和了解它。 引用MDN中的描述:

The currentColor keyword represents the calculated value of the element's color property. It allows to make the color properties inherited by properties or child's element properties that do not inherit it by default. It can also be used on properties that inherit the calculated value of the element's color property and will be equivalent to the inherit keyword on these elements, if any.

我們知道如果你不指定border-color的值,它會預設填充color的值:

	<style type="text/css">
	.parent{ 
		width: 100px;
		height: 100px; 
		color: red;
		border: 1px solid;
		box-shadow: 5px 5px 5px;
		text-shadow: 3px 3px 3px;
	}
	</style>
	<div class="parent">
		沒有設定邊框顏色
	</div> 

這是一個相當巧妙的技巧:如果你改變了文字的顏色,邊框顏色會自動跟著改變。這個技巧同樣適用於outline,box-shadow,text-shadow等。

二、部分例項

<style type="text/css">
.parent{ 
	width: 100px;
	height: 100px; 
	color: #333;
}
.son {
	border: 1px solid #333;
	box-shadow: 2px 2px 2px #333;
}
</style>
<div class="parent">
	<div class="son">沒有設定邊框顏色</div>
</div>

  

下面我們來使用currentColor修改上例:

<style type="text/css">
.parent{ 
	width: 100px;
	height: 100px; 
	color: #333;
}
.son {
	border: 1px solid currentColor;
	box-shadow: 5px 5px 5px currentColor;
	text-shadow: 3px 3px 3px currentColor;
}
</style>
<div class="parent">
	<div class="son">沒有設定邊框顏色</div>
</div>

當然,你也可以適用currentColor在所有你所期望的地方,像gradients、SVG、偽元素,例如:使inline svg sprites 顯示像icon fonts,像下面這樣:

svg {fill: currentColor;}

此時每個svg元素將被渲染為父元素的文字顏色,請戳view Demo

三、Support

IE9+及現代瀏覽器皆支援。

 

感謝您的閱讀,文中不妥之處還望批評指正。

 

轉載宣告:

本文標題:第一個CSS變數:currentColor

轉載請註明轉自Benjamin-專注前端開發和使用者體驗

相關文章