开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第24天,点击查看活动详情
nth-child 参数详解
-
nth-child 详解
-
注意:本质上就是选中第几个子元素
-
n 可以是数字、关键字、公式
-
n 如果是数字,就是选中第几个
-
常见的关键字有
even偶数、odd奇数 -
常见的公式如下(如果 n 是公式,则从 0 开始计算)
-
但是第 0 个元素或者超出了元素的个数会被忽略
-
-
代码演示
<style> /* 偶数 */ ul li:nth-child(even) { background-color: aquamarine; } /* 奇数 */ ul li:nth-child(odd) { background-color: blueviolet; } /*n 是公式,从 0 开始计算 */ ul li:nth-child(n) { background-color: lightcoral; } /* 偶数 */ ul li:nth-child(2n) { background-color: lightskyblue; } /* 奇数 */ ul li:nth-child(2n + 1) { background-color: lightsalmon; } /* 选择第 0 5 10 15, 应该怎么选 */ ul li:nth-child(5n) { background-color: orangered; } /* n + 5 就是从第5个开始往后选择 */ ul li:nth-child(n + 5) { background-color: peru; } /* -n + 5 前五个 */ ul li:nth-child(-n + 5) { background-color: tan; } </style>
十一、nth-child 和 nt-of-type 的区别
-
代码演示
<style> div :nth-child(1) { background-color: lightblue; } div :nth-child(2) { background-color: lightpink; } div span:nth-of-type(2) { background-color: lightseagreen; } div span:nth-of-type(3) { background-color: #fff; } </style>
-
区别
nth-child选择父元素里面的第几个子元素,不管是第几个类型nt-of-type选择指定类型的元素
十二、伪元素选择器
-
伪类选择器
-
伪类选择器注意事项
before和after必须有content属性before在内容前面,after 在内容后面before和after创建的是一个元素,但是属于行内元素- 创建出来的元素在
Dom中查找不到,所以称为伪元素 - 伪元素和标签选择器一样,权重为 1
-
代码演示
<style> div { width: 100px; height: 100px; border: 1px solid lightcoral; } div::after, div::before { width: 20px; height: 50px; text-align: center; display: inline-block; } div::after { content: '德'; background-color: lightskyblue; } div::before { content: '道'; background-color: mediumaquamarine; } </style>
十三、伪元素的案例
-
添加字体图标
p { width: 220px; height: 22px; border: 1px solid lightseagreen; margin: 60px; position: relative; } p::after { content: '\ea50'; font-family: 'icomoon'; position: absolute; top: -1px; right: 10px; }
十四、2D 转换之 translate
-
2D转换2D转换是改变标签在二维平面上的位置和形状- 移动:
translate - 旋转:
rotate - 缩放:
scale
-
translate语法- x 就是 x 轴上水平移动
- y 就是 y 轴上水平移动
transform: translate(x, y) transform: translateX(n) transfrom: translateY(n) -
重点知识点
2D的移动主要是指 水平、垂直方向上的移动translate最大的优点就是不影响其他元素的位置translate中的100%单位,是相对于本身的宽度和高度来进行计算的- 行内标签没有效果
-
代码演示
div {
background-color: lightseagreen;
width: 200px;
height: 100px;
/* 平移 */
/* 水平垂直移动 100px */
/* transform: translate(100px, 100px); */
/* 水平移动 100px */
/* transform: translate(100px, 0) */
/* 垂直移动 100px */
/* transform: translate(0, 100px) */
/* 水平移动 100px */
/* transform: translateX(100px); */
/* 垂直移动 100px */
transform: translateY(100px)
}
十五、让一个盒子水平垂直居中
- 看代码
十六、2D 转换 rotate
-
rotate 旋转
2D旋转指的是让元素在二维平面内顺时针或者逆时针旋转
-
rotate语法/* 单位是:deg */ transform: rotate(度数) -
重点知识点
rotate里面跟度数,单位是deg- 角度为正时,顺时针,角度为负时,逆时针
- 默认旋转的中心点是元素的中心点
-
代码演示
img:hover { transform: rotate(360deg) }