详解CSS属性选择器

详解CSS属性选择器

CSS属性选择器是根据标签属性或属性值选择元素的方式。

1. [attribute] 选择器

最简单属性选择器是根据特定属性选择元素。下面示例选择带有title属性的所有元素:

[title] {
    color: blue;
}

也可以限制选择特定的html元素,即把属性选择器放在元素后面。下面示例abbr[title]仅匹配标签:

abbr[title] {
    color: red;
}

2. [attribute=“value”] 选择器

[attribute=“value”] 根据特定属性值进行选择。下面示例匹配所有元素,其中要求type属性为"submit"。

input[type="submit"] {
    border: 1px solid green;
}

3. [attribute~=“value”] 选择器

[attribute~=“value”] 选择元素属性值是空格分隔的值列表,其中正好有一个值为“value”。
下面示例匹配class属性值包括空格分隔的值,其中一个值为“warning".例如,它匹配有class值为warning", “alert warning” 等。

[class~="warning"] {
    color: #fff;
    background: red;
}

4. [attribute|=“value”] 选择器

[attribute|=“value”] 根据属性值选择元素。值可以正好为“value”或以“value”开头并跟上“-”。一般用于语言子码匹配。

下面示例匹配lang属性包括以“en”开头或该值后面有连字符和更多字符。举例:匹配"en", “en-US”, "en-GB"等,不匹配 “US-en”, “GB-en”:

[lang|=en] {
    color: #fff;
    background: blue;
}

5. [attribute^=“value”] 选择器

[attribute^=“value”] 选择指定属性其值的前缀为“value”。下面示例给所有外部链接增加icon表示其可以在新窗口打开:

a[href^="http://"] {
    background: url("external.png") 100% 50% no-repeat;
    padding-right: 15px;
}

6. [attribute$=“value”] 选择器

[attribute$=“value”]选择指定属性其值已"value"结尾。下面示例给所有pdf链接增加一个pdf图标:

a[href$=".pdf"] {
    background: url("pdf.png") 0 50% no-repeat;
    padding-left: 20px;
}

7. [attribute*=“value”] 选择器

[attribute*=“value”]选择指定属性其值至少包括一次“value”作为子串。
下面示例匹配所有带class属性且其值包括"warning"的元素。举例匹配"warning", “alert warning”, “alert-warning” 或者 “alert_warning” 等:

[class*="warning"] {
    color: #fff;
    background: red;
}

8. 应用示例

下面示例对于标签元素没有class或id,这里通过属性进行样式设定:

input[type="text"], input[type="password"] {
    width: 150px;
    display: block;
    margin-bottom: 10px;
    background: yellow;
}
input[type="submit"] {
    padding: 2px 10px;
    border: 1px solid #804040;
    background: #ff8040;
}

9. 总结

本文介绍了样式表的属性选择器,一共介绍7中属性选择器用法及一个示例应用。

发布了395 篇原创文章 · 获赞 761 · 访问量 143万+

猜你喜欢

转载自blog.csdn.net/neweastsun/article/details/104125223