CSS选择器
基础
- 标签选择器
- 类选择器
- id选择器
复合选择器
- 后代选择器
语法:
[元素1]+空格+[元素2]{}
eg:ol li{}
选择 ol的后代li
- 子选择器
[元素1]>[元素2]{} 只选择子元素
- 并集选择器
[元素1]+,+[元素2] 语法规定:竖着写
- 伪类选择器
语法: div:first-child,解释:选择div的第一个孩子
- 链接伪类选择器 a:[link/visited/hover/active]
- focus伪类选择器 input:focus 把获得光标的input标签选择出来
- [选择器1] + [选择器2]
选择所有选择器1后的选择器2(兄弟关系的结点,且只选最近的一个兄弟
CSS3新增选择器
属性选择器
根据元素特定的属性来算则元素,可以不借助类或id进行选额
示例
<!-- 1. 利用属性选择器就可以不用借助于类或者id选择器 -->
<!-- <input type="text" value="请输入用户名">
<input type="text"> -->
<!-- 2. 属性选择器还可以选择属性=值的某些元素 重点务必掌握的 -->
<input type="text" name="" id="">
<input type="password" name="" id="">
<!-- 3. 属性选择器可以选择属性值开头的某些元素 -->
<div class="icon1">小图标1</div>
<div class="icon2">小图标2</div>
<div class="icon3">小图标3</div>
<div class="icon4">小图标4</div>
<div>我是打酱油的</div>
<!-- 4. 属性选择器可以选择属性值结尾的某些元素 -->
<section class="icon1-data">我是安其拉</section>
<section class="icon2-data">我是哥斯拉</section>
<section class="icon3-ico">哪我是谁</section>
/* 必须是input 但是同时具有 value这个属性 选择这个元素 [] */
/* input[value] {
color:pink;
} */
/* 只选择 type =text 文本框的input 选取出来 */
input[type=text] {
color: pink;
}
/* 选择首先是div 然后 具有class属性 并且属性值 必须是 icon开头的这些元素 */
div[class^=icon] {
color: red;
}
section[class$=data] {
color: blue;
}
div.icon1 {
color: skyblue;
}
/* 类选择器和属性选择器 伪类选择器 权重都是 10 */
结构伪类选择器
根据文档结构来选择元素,常用于选择父级元素种的子元素
/* 1. 选择ul里面的第一个孩子 小li */
ul li:first-child {
background-color: pink;
}
/* 2. 选择ul里面的最后一个孩子 小li */
ul li:last-child {
background-color: pink;
}
/* 3. 选择ul里面的第2个孩子 小li */
ul li:nth-child(2) {
background-color: skyblue;
}
ul li:nth-child(6) {
background-color: skyblue;
}
nth-child(n)的运用,n可以是数字、公式或者关键字
/* 1.把所有的偶数 even的孩子选出来 */
ul li:nth-child(even) {
background-color: #ccc;
}
/* 2.把所有的奇数 odd的孩子选出来 */
ul li:nth-child(odd) {
background-color: gray;
}
/* 3.nth-child(n) 从0开始 每次加1 往后面计算 这里面必须是n 不能是其他的字母 选择了所有的孩子*/
/* ol li:nth-child(n) {
background-color: pink;
} */
/* 4.nth-child(2n)母选择了所有的偶数孩子 等价于 even*/
/* ol li:nth-child(2n) {
background-color: pink;
}
ol li:nth-child(2n+1) {
background-color: skyblue;
} */
/*从第3个开始选,到最后(包含第三个)*/
/* ol li:nth-child(n+3) {
background-color: pink;
} */
/*选择前3个元素,包含第3个*/
ol li:nth-child(-n+3) {
background-color: pink;
}
nth-child
和nth-of-type(n)
的区别
编号方式不同
nth-child会先把孩子结点全部编上号,然后再拿相应的编号的孩子结点来查看标签是否匹配。
nth-of-type则会先选出匹配的孩子结点,再依次编号。选出对应编号的结点
<!-- 区别 -->
<section>
<p>光头强</p>
<div>熊大</div>
<div>熊二</div>
</section>
ul li:first-of-type {
background-color: pink;
}
ul li:last-of-type {
background-color: pink;
}
ul li:nth-of-type(even) {
background-color: skyblue;
}
/* nth-child 会把所有的盒子都排列序号 */
/* 执行的时候首先看 :nth-child(1) 之后回去看 前面 div */
section div:nth-child(1) {
background-color: red;
}
/* nth-of-type 会把指定元素的盒子排列序号 */
/* 执行的时候首先看 div指定的元素 之后回去看 :nth-of-type(1) 第几个孩子 */
section div:nth-of-type(1) {
background-color: blue;
}
伪元素选择器
实际上使用了CSS创建的新标签,不需要创建html标签,从而简化html的结构
before和after都是一个行内元素,分别放在div盒子中的最前面和最后面,就像这样。且占用位置。
伪元素的使用:字体图标的使用
伪元素的使用:仿土豆网显示遮罩
伪元素的使用是文档结构更加清晰,而且代码写的更简单
伪元素清除浮动
PS:单冒号是为了兼容低版本的浏览器
闭合浮动(加强版):