Attribute Selector 属性选择器

匹配含有某种属性或者属性值符合某种条件或者不符合某种条件的元素。

语法:

属性选择器有下面几种语法格式:

  • [attribute]:直接匹配含有某种属性的元素,例如[href]{color:red}
  • [attribute="value"]:匹配属性值等于某值的元素。例如input[type="submit"] {color:green}
  • [attribute~="value"]:匹配属性值中含有某种属值的元素。例如[class~="warning"] {color:red},匹配 <p class="warning"> 和 <strong class="important warning"> 以及 <div class="warning highlight">,但不会匹配<p class="my-warning"> 或者 <ul class="warnings">
  • [attribute|="value"]:匹配属性值是 value 或者以 value 开头、紧接着是 _ 符号的元素。例如[lang |="en"] 匹配:<p lang="en"> 或者 <p lang="en-us">
  • [attribute^="value"]:匹配以指定属性值开头的元素。
  • [attribute$="value"]:匹配以指定属性值结尾的元素。
  • [attribute*="value"]:匹配属性值中含有指定属性值的元素。例如:a[href*="aspx.cc"] {}
  • [ns|attribute]:匹配带有指定名称空间的属性值。

浏览器支持: Internet ExplorerFirefoxChromeOperaSafari

注意:

尽管 [id="foo"]和 #foo 匹配相同的元素,但它们是不同的优先权级别。

例子 1:

<style>
input[type="text"] { border:2px solid red }
</style>

<p>这个输入框的边框不会变成红色:<input type="password" value="孟宪会之精彩世界 CSS3 中文参考" /></p>
<p>这个输入框的边框会变成红色:<input type="text" value="孟宪会之精彩世界 CSS3 中文参考" /></p>
<p>这个输入框的边框不会变成红色:<input value="孟宪会之精彩世界 CSS3 中文参考" /></p>
上面的代码中,只有设置了type="text"的输入框的边框才变成红色。测试结果:Internet Explorer 7, Internet Explorer 8,Internet Explorer 9,Firefox 4,Opera 11,Safari 5,Chrome 10 都支持该属性,但 Internet Explorer 7, Internet Explorer 8 中 没有设置type的文本框也变成了红色的边框。
本属性最后更新时间:2011-4-26 9:19:23