锚伪类:
1.a:link 未访问链接时属性
2.a:visited 访问后的属性
3.a:hover 鼠标放上去时的属性
4.a:active 点击后的属性
(注意:使用这4个时候一定要按1234的顺序写,否则容易出错)
案例:
<style>
a:link {
color: blue;
}
a:visited {
color: yellow;
}
a:hover {
color: red;
}
a:active {
color: pink;
}
</style>
<body>
<a href="#">我是个链接</a>
</body>
结构伪类选择器
E:first-child 匹配父元素的第一个子元素E
E:last-child 匹配父元素的最后一个子元素E
E:nth-child(n) 匹配父元素的第n个子元素E
E:first-of-type 指定类型E的第一个
E:last-of-type 指定类型E的最后一个
E:nth-of-type(n) 指定类型E的第n个
其中nth-child(n)
-
n 可以是数字、关键字、公式
-
n 如果是数字,就是选中第几个
-
常见的关键字有
even偶数、odd奇数 -
常见的公式如下(如果 n 是公式,则从 0 开始计算)
-
但是第 0 个元素或者超出了元素的个数会被忽略
| 公式 | 取值 |
|---|---|
| 2n | 偶数 |
| 2n+1 | 奇数 |
| 5n | 5 10 15 |
| n+5 | 第5个开始(包含第5个) |
| -n+5 | 前5个(包含第5个) |
案例
<style>
ul li:first-child {
background-color: lightseagreen;
}
ul li:last-child {
background-color: lightcoral;
}
/* 偶数 */
ul li:nth-child(even) {
background-color: aquamarine;
}
/* 奇数 */
ul li:nth-child(odd) {
background-color: blueviolet;
}
/*n 是公式,从 0 开始计算 */
ul li:nth-child(n) {
background-color: lightcoral;
}
/* 偶数 */
ul li:nth-child(2n) {
background-color: lightskyblue;
}
/* 奇数 */
ul li:nth-child(2n + 1) {
background-color: lightsalmon;
}
/* 选择第 0 5 10 15, 应该怎么选 */
ul li:nth-child(5n) {
background-color: orangered;
}
/* n + 5 就是从第5个开始往后选择 */
ul li:nth-child(n + 5) {
background-color: peru;
}
/* -n + 5 前五个 */
ul li:nth-child(-n + 5) {
background-color: tan;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</body>
nth-child(n)与nth-of-type(n)的区别
-
nth-child选择父元素里面的第几个子元素,不管是第几个类型 -
nt-of-type选择指定类型的元素
案例
<style>
div p:nth-child(1) {
background-color: pink;
}
/* 下面的不会选择到,因为第一个是p标签,还定义了span,所以选择不到 */
div span:nth-child(1) {
background-color: red;
}
/* 而of-type就会选择相应的类型 */
div span:nth-of-type(1) {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>我是个p标签</p>
<span>我是个span标签</span>
<span>我是个span标签</span>
</div>
</body>
伪元素
::before 在元素内部前面插入内容
::after 在元素内部后面插入内容
注意事项
-
before和after必须有content属性 -
before在内容前面,after 在内容后面 -
before和after创建的是一个元素,但是属于行内元素 -
创建出来的元素在
Dom中查找不到,所以称为伪元素 -
伪元素和标签选择器一样,权重为 1
案例:
<style>
div {
width: 100px;
height: 100px;
border: 1px solid lightcoral;
}
div::after,
div::before {
width: 20px;
height: 50px;
text-align: center;
display: inline-block;
}
div::after {
content: '德';
background-color: lightskyblue;
}
div::before {
content: '道';
background-color: mediumaquamarine;
}
</style>
</head>
<body>
<div></div>
</body>
本文详细介绍了CSS中的锚伪类、结构伪类选择器以及伪元素的用法,包括未访问链接、已访问链接、鼠标悬停和活动状态的样式设置,还有 nth-child 和 nth-of-type 的区别及用法示例。此外,通过案例展示了如何在元素前后插入内容。这些知识对于理解和优化网页样式至关重要。
2642

被折叠的 条评论
为什么被折叠?



