文章目录
1. 并集选择器
选中多个选择器对应的元素。一般用来设置表格的边框。
2. 交集选择器
同时选中符合条件的元素。
3. 后代选择器
用来选择元素或元素组的后代,需要先写祖先,再写后代。
4. 子代选择器
选中指定元素中,符合要求的子元素,父级标签写在前面,子级标签写在后面,中间有一个**>**。
5. 兄弟选择器
5.1. 相邻兄弟选择器
选中指定元素后,符合条件的相邻兄弟元素,二者是同一个父亲。
5.2. 通用兄弟选择器
选中指定元素后,符合条件的所有兄弟元素,只要是同一个父元素,都会被选择。
6. 属性选择器
选中具有某种属性的元素。
语法:
- [属性名] 选中具有某个属性的元素。
- [属性名=“值”] 选中包含某个属性,且属性值等于给定值的元素。
- [属性名^=“值”] 选中包含某个属性,且属性值以给定值开头的元素。
- [属性名$=“值”] 选中包含某个属性,且属性值以给定值结尾的元素。
- [属性名*=“值”] 选择包含某个属性,属性值包含给定值的元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* 需求:选择跟div相邻的p元素 设置成红色 */
/* 方式一:通过属性选择器(通过属性名) */
[data] {
color: red;
}
/* 方式二:通过属性选择器(通过属性名=属性值) */
[data="d1"] {
color: green;
}
</style>
</head>
<body>
<div>
<span>我是span标签</span>
<p data="d1">我是带有属性的p标签</p>
</div>
<p>我是p标签</p>
<p data="d1">我是带有属性的p标签</p>
</body>
</html>
7. 伪类选择器
选中特殊状态的元素 。
7.1. 动态伪类
伪类 | 属性 |
---|---|
:link | 超链接未被访问的状态 |
:visited | 超链接访问过的状态 |
:hover | 鼠标悬停在元素上的状态 |
:active | 元素激活的状态 |
:focus | 获取焦点的元素 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>07-CSS扩展选择器-伪类选择器</title>
<style>
a,
span {
font-size: 50px;
}
a:link {
color: red;
}
a:visited {
color: green;
}
a:hover {
color: blue;
}
a:active {
color: yellow;
}
</style>
</head>
<body>
<a href="https://douglas.blog.csdn.net/">博客</a>
<span>文字</span>
</body>
</html>
7.2. 结构伪类
伪类 | 属性 |
---|---|
:first-child | 所有兄弟元素中的第一个 |
:last-child | 所有兄弟元素中的最后一个 |
:nth-child(n) | 所有兄弟元素中的第 n 个(元素类型没有限制) |
:first-of-type | 所有同类型兄弟元素中的第一个 |
:last-of-type | 所有同类型兄弟元素中的最后一个 |
:nth-of-type(n) | 所有同类型兄弟元素中的 第 n 个(元素类型有限制) |
:root | 根元素 |
7.3. 否定伪类
:not
(选择器) 排除满足括号中条件的元素。
8. 伪元素选择器
在 html 骨架中,并没有通过 html 标签去创建元素,而是通过 css 模拟出来的标签效果。
一般用在页面的非主体部分,某些情况下可以简化代码。
区别:
- 普通元素:通过 html 标签生成的。
- 伪元素:通过 css 模拟出来的标签效果。
- 本质区别:是否在 html 中创建了新的标签。
常用的伪元素:
伪元素 | 属性 |
---|---|
::first-letter | 选中元素中的第一个文字 |
::first-line | 选中元素中的第一行文字 |
::placeholder | 选中输入框的提示文字 |
::before | 在元素最开始的位置,创建一个子元素(必须用 content 属性指定内容) |
::after | 在元素最后的位置,创建一个子元素(必须用 content 属性指定内容) |
9. Google 改进案例
使用动态伪类实现鼠标放在单词上变色。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>05-CSS扩展选择器-Google案例-改进</title>
<style>
/* 设置颜色 */
.c1 {
color: blue;
}
.c2 {
color: red;
}
.c3 {
color: yellow;
}
.c4 {
color: green;
}
/* 设置字体 */
span {
font-size: 100px;
}
span:hover {
color: orange;
cursor: pointer;
}
</style>
</head>
<body>
<span class="c1">G</span>
<span class="c2">o</span>
<span class="c3">o</span>
<span class="c1">g</span>
<span class="c4">l</span>
<span class="c2">e</span>
</body>
</html>