后代选择器
语法:
<style>
父选择器 子选择器 {
属性:属性值;
属性:属性值;
}
</style>
中间使用空格隔开
只要有标签嵌套就可以使用后代选择器
<style>
ul li {
color: red;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
并集选择器
(CSS选择器分组)是各个选择器通过,连接而成的,通常用于集体声明。
如果某些选择器定义的相同样式,就可以利用并集选择器,可以让代码更简洁。
语法:
<style>
选择器1,选择器2 {
属性:属性值;
属性:属性值;
}
</style>
使用逗号隔开,两个选择器都会使用同一种样式
<style>
li,
span {
color: red;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<span>我是span</span>
</body>
交集选择器
交集选择器 是 并且的意思。 即...又...的意思
语法:
<style>
标记选择器.类别选择器 {
属性1: 值1;
}
</style>
标记选择器后写类别选择器,只有同时满足这两个条件的才会使用这个样式
<style>
li {
color: red;
}
li.teshuli {
color: green;
}
</style>
<body>
<ul>
<li>1</li>
<li class="teshuli">2</li>
<li>3</li>
</ul>
</body>
兄弟选择器
如果需要选择紧接在另一个元素后的元素,而且二者有相同的父元素,
可以使用相邻兄弟选择器
<!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>
h1+p {
color: red;
}
</style>
</head>
<body>
<div>
<h1>111</h1>
<p>222</p>
<p>333</p>
</div>
</body>
</html>
子元素选择器
语法:
<style>
父元素>子元素 {
属性1: 值1;
}
</style>
一个元素是另一个元素的子元素,使用>号隔开
<!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>
ul>li {
color: red;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
</html>
属性选择器
<style>
/* 存在title属性的<a> 元素 */
a[title] {
color: purple;
}
/* 存在href属性并且属性值匹配"https://example.org"的<a> 元素 */
a[href="https://example.org"] {
color: green;
}
/* 存在href属性并且属性值包含"example"的<a> 元素 */
a[href*="example"] {
font-size: 2em;
}
/* 存在href属性并且属性值结尾是".org"的<a> 元素 */
a[href$=".org"] {
font-style: italic;
}
/* 存在class属性并且属性值包含以空格分隔的"logo"的<a>元素 */
a[class~="logo"] {
padding: 2px;
}
</style>
结构伪类选择器
选择器 | 作用 |
---|---|
first-child | 匹配子集的第一个元素 |
last-child | 匹配子集的最后一个元素 |
nth-child(n) | 根据索引n匹配值 |
nth-last-child(n) | 根据索引n匹配值,索引从最后一个开始数 |
only-child | 当标签下有且仅有一个匹配的元素时,才会有作用,如果有多个元素不会有作用 |
状态伪类选择器
<style>
/* 未访问的链接 */
a:link {
}
/* 已访问的链接 */
a:visited {
}
/* 鼠标移动到链接上 */
a:hover {
}
/* 选定的链接 */
a:active {
}
</style>