关于css设置第n个元素

1、3个元素一行,间距设置
方法一:设置中间元素margin-left,margin-right,获取第2、5、8、11…元素,找到公式最重要,公式为3n+2(下面会附上公式讲解),所以就是

.class:nth-child(3n+2){
	margin:0 20px;
}

方法二:设置每个元素margin-right,然后再找到每一行的最后一个元素即3的倍数(公式3n+3)元素margin-right:0

.class{
	margin-right:20px;
}
.class:nth-child(3n+3){
	margin-right:0;
}
/*3n也可,反正第0个也没有*/

提一下另一种方法,跟主题偏离了,但也算个知识点
用flex布局,justify-content: space-between;但不适合元素个数不定,比如第二行只有两个元素,不能靠左显示。

公式计算原理
拿上面的3n+2,n就是0,1,2,3,4,5…,计算就是30+2,31+2,3*2+2依次类推

未完待续…

猜你喜欢

转载自blog.csdn.net/qq_37291064/article/details/92840304