批改状态:合格
老师批语:很棒的
元素选择器
<div class="first"><div class="time" id="to">1</div><div class="time" title="aaa">2</div></div>
div{...},class选择器.time{...} , id选择器#to{} , 属性选择器.time[title="aaa"]{}。分为后代选择器、父子选择器、同级相邻选择器、同级所有选择器。
| 序号 | 选择器 | 操作符 | 描述 | 举例 |
|---|---|---|---|---|
| 1 | 后代选择器 | 空格 |
选择当前元素的所有后代元素 | div p, body * |
| 2 | 父子选择器 | > |
选择当前元素的所有子元素 | div > h2 |
| 3 | 同级相邻选择器 | + |
选择拥有共同父级且相邻的元素 | li.red + li |
| 4 | 同级所有选择器 | ~ |
选择拥有共同父级的后续所有元素 | li.red ~ li |
例如
<div class="first"><div class="time">1</div><div class="time aaa">2</div><div class="time">3</div><div class="time">4</div><div class="time">5</div></div>
后代选择器.first div{}选中了所在12345的div,父子选择器body > div{}选中了.first这个div,同级相邻选择器.time.aaa + .time{}选中了3这个div,同级所有选择器.time.aaa ~ .time{}选中了345这3个div。
| 场景 | 描述 |
|---|---|
| 结构伪类 | 根据子元素的位置特征进行选择 |
| 表单伪类 | 根据表单控件状态特征进行选择 |
| 序号 | 选择器 | 描述 | 举例 |
|---|---|---|---|
| 1 | :first-child |
匹配第一个子元素 | div :first-child |
| 2 | :last-child |
匹配最后一个子元素 | div :last-child |
| 3 | :only-child |
选择元素的唯一子元素 | div :only-child |
| 4 | :nth-child(n) |
匹配任意位置的子元素 | div :nth-child(n) |
| 5 | :nth-last-child(n) |
匹配倒数任意位置的子元素 | div :nth-last-child(n) |
<style>/* .container下的第一个子元素 */.container > :first-child {background-color: #ecbfbf;}/* .container下的最后一个子元素 */.container > :last-child {background-color: crimson;}/* .container下的第4个子元素 */.container > :nth-child(4) {background-color: darkblue;}/* .container下的8个子元素 */.container > :nth-last-child(2) {background-color: darkgoldenrod;}</style><body><div class="container"><div class="item">1</div><div class="item">2</div><div class="item">3</div><div class="item">4</div><div class="item center">5</div><div class="item">6</div><div class="item">7</div><div class="item">8</div><div class="item">9</div></div></body>
效果图
| 序号 | 选择器 | 描述 | 举例 |
|---|---|---|---|
| 1 | :first-of-type |
匹配按类型分组后的第一个子元素 | div :first-of-type |
| 2 | :last-of-type |
匹配按类型分组后的最后一个子元素 | div :last-of-type |
| 3 | :only-of-type |
匹配按类型分组后的唯一子元素 | div :only-of-type |
| 4 | :nth-of-type() |
匹配按类型分组后的任意位置的子元素 | div :nth-of-type(n) |
| 5 | :nth-last-of-type() |
匹配按类型分组后倒数任意位置的子元素 | div :nth-last-of-type(n) |
“-n”表示获取前面一组元素,正数表示从指定位置获取余下元素 (奇数odd)(偶数even)
<style>/* 选中p标签最后一个 */.conser p:nth-last-of-type(1) {background-color: darkgreen;}/* h6标签第一个 */.conser h6:first-of-type {background-color: darkorange;}/* h6标签最后一个 */.conser h6:last-of-type {background-color: darkslategrey;}/* 选中3及以前的h4标签 */.conser h4:nth-of-type(-n + 3) {background-color: deepskyblue;}</style><body><div class="conser"><p>我们都是好孩子</p><p>我们都是好孩子</p><h6>我是好人</h6><h6>我是好人</h6><h6>我是好人</h6><h4>1</h4><h4>2</h4><h4>3</h4><h4>4</h4><h4>5</h4></div></body>
效果图
学习了css中的各类选择器
伪类选择器是重点
目前自己还有知识点需要掌握
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号