伪类选择器
在一个ul标签里往往有非常多个li标签 那么我如果只想选择其中的某些个li标签来加入填充背景或者其他css样式就得用到child样式
选择第一个li标签
<style>
li:first-child{
background-color: aqua;
}
</style>
选择最最后一个li标签
<style>
li:last-child{
background-color: aqua;
}
</style>
选择单个li标签
<style>
li:nth-child(2){
background-color: aqua;
}
</style>
利用公式来选择标签
2n偶数标签、2n-1奇数标签、5n、5的倍数标签、n+5从5开始的标签.......
<style>
li:nth-child(2n){
background-color: aqua;
}
li:nth-child(5n){
background-color: aqua;
}
li:nth-child(n+5){
background-color: aqua;
}
li:nth-child(-n+5){
background-color: aqua;
}
</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>
</head>
<style>
li:first-child{
background-color: aqua;
}
li:last-child{
background-color: aqua;
}
li:nth-child(2){
background-color: aqua;
}
li:nth-child(2n){
background-color: aqua;
}
li:nth-child(5n){
background-color: aqua;
}
li:nth-child(n+5){
background-color: aqua;
}
li:nth-child(-n+5){
background-color: aqua;
}
</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>
</html>
伪元素选择器
当我们需要在标签前面加上一个虚拟元素时 可以使用伪类构造器 一般用来装饰页面
基本语法
<style>
div::before{
content: "老鼠";
display: inline-block;
width: 100px;
height: 100px;
background-color: rgb(177, 177, 238);
}
div::after{
content:"大米";
display: block;
background-color:aquamarine;
width: 100px;
height: 100px;
}
</style>
其中before是在标签前添加一个伪元素 after是在标签后添加一个伪元素
content是必须要的属性代表内容 没有则不生效
因为默认伪元素是行内级元素 所以width和height属性加不上需要用display抓换成块级元素或者行内块级元素。
完整代码
<!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{
background-color: pink;
height: 300px;
width: 300px;
}
div::before{
content: "老鼠";
display: inline-block;
width: 100px;
height: 100px;
background-color: rgb(177, 177, 238);
}
div::after{
content:"大米";
display: block;
background-color:aquamarine;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div>
爱
</div>
</body>
</html>