2.css的选择器
1.基本选择器
-
标签选择器
p{
}
-
id选择器
id名{
}
-
类选择器
.class{
}
-
通配符选择器
*{
}
2.包含选择器
-
自代选择器
.a>li{
}
选择直系后代
-
后代选择器
.a li{
}
选择全部后代
3.复合选择器
由几个不同的选择器结合
div
p
span{
}
4.属性选择器
5.伪类选择器
- 链接/访问伪类::link、:visited、:hover、:active、:focus。这些伪类主要用于样式化超链接。
- 动态伪类选择器::active, :hover, :focus。这些伪类主要用于改变元素在不同状态下的样式,例如当用户悬停或单击元素时。
- 目标伪类::target。此伪类选取活动链接(被点击的链接)。
- 语言伪类::lang。使用这个伪类可以根据元素的语言为其设置样式。
- 结构性伪类:
- 子元素伪类::first-child, :last-child, :nth-child(n), :nth-last-child(n), :only-child。
- 类型伪类::first-of-type, :last-of-type, :nth-of-type(n), :nth-last-of-type(n), :only-of-type。
- 状态伪类::enabled, :disabled, :checked。这些用于选择和改变表单元素的样式。
- 否定伪类::not()。这个伪类排除了一部分元素,并选择其余元素。
- 空元素伪类::empty。此伪类用于选取没有子元素的元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>伪类选择器</title>
<style>
a:link {
color: pink;
}
a:visited {
color: red;
}
/* :hover 鼠标悬停 */
a:hover {
/* cursor 鼠标样式 */
cursor: pointer;
font-size: 40px;
}
a:active {
font-size: 70px;
}
div {
width: 300px;
height: 300px;
background-color: pink;
}
/* s a:hover+div {
background-color: blue;
} */
a:hover+div {
/* background-color: greenyellow; */
display: none;
}
</style>
</head>
<body>
<a href="#">关闭广告</a>
<div></div>
<div></div>
</body>
</html>
6.结构伪类选择器
- 子元素伪类:
- :first-child:选择其父元素的第一个子元素。
- :last-child:选择其父元素的最后一个子元素。
- :nth-child(n):选择其父元素的第n个子元素。
- :nth-last-child(n):选择其父元素的第n个子元素,从最后一个子元素开始计数。
- :only-child:选择其父元素唯一的子元素。
- 类型伪类:
- :first-of-type:选择每个父元素的第一个特定类型的子元素。
- :last-of-type:选择每个父元素的最后一个特定类型的子元素。
- :nth-of-type(n):选择每个父元素的第n个特定类型的子元素。
- :nth-last-of-type(n):选择每个父元素的第n个特定类型的子元素,从最后一个开始计数。
- :only-of-type:选择其父元素的唯一的特定类型的子元素。
<!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:first-child {
background-color: pink;
}
ul li:last-child {
background-color: green;
}
ul li:nth-child(3) {
background-color: blue;
}
ul li:nth-of-type(4) {
background-color: chartreuse;
}
</style>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</body>
</html>
7.伪元素选择器
伪元素选择器是CSS选择器的一种,用于选择一个元素的特定部分,而这个部分并不能被HTML元素表示。伪元素能让你为一些特定的元素部分设计样式。常用的伪元素包括:
- ::before - 在元素内容的前面插入内容。这个伪元素常用于插入装饰性的内容。
- ::after - 在元素内容的后面插入内容。和 ::before 类似,这个伪元素也常用于插入装饰性的内容。
- ::first-letter - 选择块级元素第一行的第一个字母。可以用于设计“首字下沉”等效果。
- ::first-line - 选择块级元素的第一行。用于改变某个块级元素的第一行的样式。
- ::selection - 选择用户选择的元素部分。例如,你可以改变用户选中文本的颜色和背景色。
- ::placeholder - 选择输入框的占位符文本。允许你自定义输入框的占位符样式。
注意,伪元素使用两个冒号(::)前缀来与伪类选择器区分。早期的CSS版本中的伪元素(like ::before and ::after)也接受一个冒号的前缀,但是现代的标准和浏览器推荐使用两个冒号的前缀。
p::before {
content: "前缀";
color: blue;
}