CSS选择器-属性选择器
简单属性选择
h1[class] {color: red;}
<h1 class="hoopla">Hello</h1>
<h1 class="severe">Serenity</h1>
在XML文档中,属性原则器相当有用,因为XML语言主张要针对元素和属性的用途指定元素名和属性名。
选择以后moons属性的所有planet元素,使之显示为粗体,以便能更关注有moons的行星:
planet[moons] {font-weight: bold;}
<planet>Venus</planet>
<planet moons="1">Earth</planet>
<planet moons="2">Mars</planet>
还可以根据多个属性进行选择,只需要将属性选择器链接在一起即可。
同时将有href和title属性的HTML超链接文本设置为粗体:
a[href][title] {font-weight: bold;}
以下标记只有第一个链接变成粗体:
<a href="http://www.wr.org/" title = "W3C Home">W3C</a><br />
<a href="http://www.webstandards.org">Standards Info</a><br />
<a title="Not a link">dead.letter</a>
根据具体属性值选择
planet[moons="1"] {font-weight: bold;}
<planet>Venus</planet>
<planet moons="1">Earth</planet>
<planet moons="2">Mars</planet>
需要注意的是,这种格式要求必须与属性值完全匹配。如果遇到的值本身包含一个用空格分隔的值列表,匹配就会出问题。要根据具体的属性值匹配这个元素,唯一写法:
<planet type="barren rocky">Mercury</planet>
planet[type="barren rocky"] {font-weight: bold;}
根据部分属性值选择
<p class="urgent warning">When handling plutonium, care must be taken to avoid the formation of a critical mass.</p>
选择class属性中包含warning的元素:
p[class~="warning"] {font-weight: bold;}
等价于点号类名记法: p.warning
和 p[class~="warning"]
应用到HTML文档中是等价的。
子串匹配属性选择器
类型 | 描述 |
---|---|
[foo^=”bar”] | 选择foo属性值以”bar”开头的所有元素 |
[foo$=”bar”] | 选择foo属性值以”bar”结尾的所有元素 |
[foo*=”bar”] | 选择foo属性值中包含子串”bar”的所有元素 |
目前只有Safari、基于Gecko的游览器、Opera和IE7/Win对这种子串选择器提供支持。
特定属性选择类型
*[lang|="en"] {color: white;}
常用于匹配语言值,但可以用于任何属性及其值。选择lang属性等于en或者以en-开头的所有元素。