基础选择器
1. 元素选择器
…
2. 类选择器
/* 多类选择器 */
.class_1.class_2.class_3 {
...
}
3. id 选择器
…
高级选择器
1. 后代选择器
h1 em {color:red;}
2. 子元素选择器
h1 > strong {color:red;}
3. 相邻兄弟选择器
h1 + p {margin-top:50px;}
4. 属性选择器
选择方法 | 描述 |
---|---|
[attribute] | 指定属性 |
[attribute=value] | 指定属性和值 |
- | - |
[attribute~=value] | 属性值中包含指定值 ( 单词 ) |
[attribute| =value] | 以指定值单词开头的属性值 ( 单词 ) |
- | - |
[attribute^=value] | 属性值以指定值开头的 |
[attribute$=value] | 属性值以指定值结尾的 |
[attribute*=value] | 匹配属性值中包含指定值的每个元素 |
*[title] {color:red;}
a[href] {color:red;}
a[href][title] {color:red;}
/* 属性与属性值必须完全匹配 */
a[href="http://www.w3school.com.cn/about_us.asp"] {color: red;}
a[href="http://www.w3school.com.cn/"][title="W3School"] {color: red;}
p[class="important warning"] {color: red;} /* p.important 等价 p[class="important"] */
/* 根据部分属性值选择 */
p[class~="important"] {color: red;}
img[title~="Figure"] {border: 1px solid gray;}
a[href*="w3school.com.cn"] {color: red;}
假设一个 HTML 文档中有一系列图片,其中每个图片的文件名都形如 figure-1.jpg 和 figure-2.jpg(注意不是 figure_1.jpg 和 figure_2.jpg) 就可以使用以下选择器匹配所有这些图像:
img[src|="figure"] {border: 1px solid gray;}
伪类
属性 | 描述 |
---|---|
:hover | 当鼠标悬浮在元素上方时 |
:active | 向被激活的元素添加样式 |
- | - |
:link | 向未被访问的链接添加样式 |
:visited | 向已被访问的链接添加样式 |
- | - |
:focus | 向拥有键盘输入焦点的元素添加样式 |
- | - |
:first-child | 向元素的第一个子元素添加样式 |
:lang | 向带有指定 lang 属性的元素添加样式 |
a:hover {color: #FF00FF} /* 当有鼠标悬停在链接上 */
a:active {color: #0000FF} /* 被选择的链接 */
a:link {color: #FF0000} /* 未访问的链接 */
a:visited {color: #00FF00} /* 已访问的链接 */
input[type="userName"]:focus {color: #FF0000} /* input等输入框输入聚焦时 */