CSS PropertySelectors
CSS attribute selectors are used to select HTML elements based on their attributes or attribute values.
Attribute selectors can help you style elements without needing to add classes or IDs to them.
Note:IE7 and IE8 require a declaration!DOCTYPEAttribute selectors are only supported from IE7 onward! IE6 and lower versions do not support attribute selectors.
The following are common CSS attribute selectors:
1、[attribute]
Selects all elements with a specified attribute (regardless of the attribute value).
/* 选择所有具有 `type` 属性的元素 */
[type] {
border: 1px solid red;
}
2、[attribute="value"]
Selects elements whose specified attribute and value exactly match a specified value.
/* 选择所有 `type` 属性等于 `text` 的元素 */
[type="text"] {
background-color: yellow;
}
3、[attribute~="value"]
Selects elements whose attribute value contains a specified word (one of a word list separated by spaces).
/* 选择属性值中包含 `button` 的元素 */
[class~="button"] {
font-weight: bold;
}
4、[attribute|="value"]
Selects elements with a specified value or an attribute value that starts with the specified value and is immediately followed by a hyphen -, commonly used for language codes.
/* 选择所有 `lang` 属性是 `en` 或者以 `en-` 开头的元素 */
[lang|="en"] {
color: green;
}
5、[attribute^="value"]
Selects elements whose attribute value starts with the specified value.
/* 选择所有 `href` 属性以 `https` 开头的链接 */
[href^="https"] {
text-decoration: none;
}
6、[attribute$="value"]
Selects elements whose attribute value ends with the specified value.
/* 选择所有 src 属性以 .jpg 结尾的图片 */
[src$=".jpg"] {
border: 2px solid blue;
}
7、[attribute*="value"]
Selects elements whose attribute value contains the specified value.
/* 选择所有 `title` 属性中包含 `tutorial` 的元素 */
[title*="tutorial"] {
font-style: italic;
}
With attribute selectors, you can easily select elements and apply specific styles based on their attributes, increasing flexibility and maintainability.
Attribute selector
The following example turns all elements containing a title attribute blue:
Attribute and value selectors
The following example changes the border style of the element with title='example':
Attribute and value selectors - multiple values
Below is an example of styling elements whose title attribute contains a specified value, using (~) to separate the attribute and value:
Below is an example of styling elements whose lang attribute contains a specified value, using (|) to separate the attribute and value:
Form Styles
Attribute selector styles do not need to use class or id forms:
Example
Try it Yourself »