批改状态:合格
老师批语:写的不错,很认真,格式也很规范!
选择器的意义:使CSS样式表能够准确选择到要改变样式的html元素。
简单选择器:使用html元素标签名称 <...> , 可直接选择一类标签;
类选择器:以 .class 表示,对应元素标签内属性 class="...",
还可以多个类复合使用以 .class1.class2 表示,CSS中使用class选择器较常见;
id选择器:以 *#id 表示,对应元素标签内属性 id="...",
通常我们可以去掉 * ,写成 #id,
现在id选择器使用场景主要在javascript中的锚点和表单中。
后代选择器:例如 .class .children,表示选择 .class下的所有 .children 元素;
父子选择器: .class > li , 选择 .class 元素下的所有 li 子元素;
同级相邻选择器: .class1.class2 + .class3 , 选择指定元素的后一个元素;
同级相邻所有选择器: .class1.class2 ~ .class1 , 选择指定元素的后所有元素;
选择指定元素的第1个子元素:
.class :first-child , .class1 > .class2:first-child;
选择指定元素的最后1个子元素:
.class1 > :last-child , .class1 > .class2:last-child;
选择指定元素的第3个子元素:
.class1 > :nth-child(3) ,注意这里是从1开始的索引
选择指定元素偶数子元素:
.class > :nth-child(2n) ,n的值递增1,从0开始,第0个元素不存在;
还可以用 .class > :nth-child(even);
选择指定元素奇数子元素:
.class > :nth-child(2n-1) , .class > :nth-child(2n+1);
还可以用 .class > :nth-child(odd);
选择指定子元素位置开始后面的所有元素:
.container > .item:nth-child(n + 4) , 表示从第4开始取后面所有元素;
选择指定元素前3个子元素:
.class1 .class2:nth-child(-n + 3);
选择指定元素后3个子元素:
.class1 .class2:nth-last-child(-n + 3);
选择指定元素倒数第2个子元素:
.class1 .class2:nth-last-child(2);
分组选择指定元素最后1个:
.class1 class2:last-of-type
分组选择指定元素第3个:
.class1 class2:nth-of-type(3)
指定元素前三个分组子元素:
.class1 class2:nth-of-type(-n + 3)
指定元素后两个分组子元素:
.class1 class2:nth-last-of-type(-n + 2)
在html代码中的用法
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>小刚的开发日志,伪类与伪元素</title></head><style>#login {display: none;}/* :target目标 */#login:target {display: block;}/* 焦点 */input:focus {background-color: chartreuse;}/* 文本选中 */input::selection {color: chocolate;background-color: cyan;}/* :not()排除不满足条件 */ul > :not(:nth-of-type(2)) {background-color: lightblue;}/* 在指定元素之前生成伪元素 */ul::before {content: "小刚的日志";color: lightcoral;}/* 在指定元素之后生成伪元素 */ul::after {content: "你好,世界";color: lightgreen;}</style><body><a href="#login">登陆</a><button onclick="location='#login'">点击登录</button><form action="" method="POST" id="login"><label for="email">邮箱:</label><input type="email" name="email" id="email" /><label for="password">密码:</label><input type="password" name="password" id="password" /><button>登陆</button></form><ul><li>1</li><li>2</li><li>3</li></ul></body></html>
以上代码运行效果

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号