css3中nth-child()的用法

555 阅读2分钟

本文正在参加「金石计划 . 瓜分6万现金大奖」

学习过程中将笔记整理跟大家分享,希望对大家也有所帮助,共同成长进步💪~
如果大家喜欢,可以点赞或留言💕~~~~,谢谢大家⭐️⭐️⭐️~~~

定义和用法

语法::nth-child(n)

说明::nth-child() 是CSS3的一个伪类选择器,匹配父元素中的第 n 个子元素,元素类型没有限制。 n 可以是一个数字,一个关键字,或者一个公式。

下面用案例来说明各个常见的情况用法

原始效果demo

<ul class="item">
  <li v-for="item in listData">
      <span>{{item.pname}}</span>
      <span>{{item.type}}</span>
      <span>{{item.LJTZJH}}</span>
      <span>{{item.LJTZWCE}}</span>
      <span>{{item.TZWCB}}</span>
      <span>{{item.YJZJSY}}</span>
  </li>
</ul>
* {
    margin: 0;
    padding: 0;
  }
.item li{
  list-style:none;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background: gray;
  border-radius: 25px;
  margin-bottom:5px;
}
.item>li>span{
  width: 15%;
  display:inline-block;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  color: #fff;
}

demo图: image.png

实现双行和单行样式效果

实现双行和单行样式效果

  • nth-child(2n)/nth-child(even): 双行样式
  • nth-child(2n+1)/nth-child(odd): 单行样式
.item li:nth-child(2n) {
    background-color: red;
}
.item li:nth-child(2n+1) {
    background-color: pink;
}

实现前三个和后三个样式效果

实现前三个和后三个样式效果

  • nth-child(-n+3)匹配最前三个子元素
  • nth-last-child(-n+3)匹配最后三个子元素
.item li:nth-child(-n+3) {
    background-color: red;
}
.item li:nth-last-child(-n+3) {
    background-color: pink;
}

特殊规律实现方法

分别实现(3,7,11) 、(3,7,11) 、(2, 5, 8, 11) 一些特殊规律的情况,这里只分别列举几个规律方便大家看出。


 /* 3,7,11 */
.item li:nth-child(4n+3) {
background-color: red;
}

/* 1,4,7,10 */
.item li:nth-child(3n+1) {
background-color: red;
}

/* 2,5,8,11 */
.item li:nth-child(3n+2) {
background-color: red;
}

最后感谢大家阅读,如果喜欢可以点赞或留言💕~~~~,谢谢大家⭐️⭐️⭐️~~~

近期热门文章

专栏推荐

推荐一下自己的专栏,欢迎大家收藏关注😊~