CSS-伪类选择器

发布于:2024-05-12 ⋅ 阅读:(155) ⋅ 点赞:(0)

结构伪类选择器 

作用:根据元素的结构关系查找元素

分类:

    

选择器 说明
元素名:first-child 查找第一个元素
元素名:last-child 查找最后一个元素
元素名:nth-child(N) 查找第N名元素

 

<!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>
     li:first-child{
        color:green;
     }
     li:nth-child(3){
        color:pink;
     }
     li:last-child{
        color:blue;
     }
    </style>
</head>
<body>
<ul>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
    <li>hello world</li>
</ul>      
</body>
</html>

网页效果:第一个元素是绿色,最后一个元素是蓝色,第三个元素是粉色 

选择器 :nth-child(公式)

功能 公式
偶数 2n
奇数 2n+1
找到x的倍数 xn
找到第x个元素以后的标签 n+x
找到第x个元素以前的标签 -n+x

  <style>

     li:nth-child(2n){
        color:pink;
     }
   
     
    </style>

偶数个元素全变成了粉色 

伪类元素选择器

作用:创建虚拟元素,用来装饰网页,由于在开发前期并不知道要放什么内容,可以用伪元素选择器来创建

选择器 说明
元素:before 在元素最前面添加一个伪元素
元素:after 在元素最后面添加一个伪元素
伪元素默认是行内显示模式

属性:content

属性值:"内容"        如果没有内容用引号留空即可

:before   选择器

<!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:before{
        content:"> ";
     }
   
     
    </style>
</head>
<body>
<div>hello world</div>
<div>hello world</div>
<div>hello world</div>
<div>hello world</div>
<div>hello world</div>  
</body>
</html>

网页效果: 

 

:after      选择器 

 div:after{
        content:"   > ";
     }

网页效果: 

 

   


网站公告

今日签到

点亮在社区的每一天
去签到