CSS选择器---nth-child&nth-of-type

nth-child

:nth-child(number)      直接匹配第number个元素复制代码
:not(:first-child)      除第一个元素以外的子元素复制代码
:nth-child(n+2)         n+2表示从第二个开始复制代码
:nth-last-child(n+2)    这样获取除最后一个div中全部的div;也能够用:not(:last-child) 复制代码
:nth-child(2n)     获取子元素中第2,4,6,8,... 的元素复制代码
:nth-child(3n)   获取子元素中第3,6,9,... 的元素复制代码
:nth-child(odd)       奇数匹配使用复制代码
:nth-child(even)        偶数匹配使用复制代码
上面的选择器能够直接在class以后,也能够在后面加span/p/div等类型后,以下:
/* analysis-res class下的除了第一个以外的元素 */
.analysis-res:not(:first-child) {
    color: #5792b1;
    font-weight: bold;
}

/*  analysis-res class下span标签中除了第一个以外的元素 */
.analysis-res span:not(:first-child) {
    color: #5792b1;
    font-weight: bold;
}
复制代码

nth-of-type

nth-of-type要是不研究一下还真容易理bash

解错,它说的是按照类型来选择,看下面这个例子。

<style>
  p:nth-of-type(1),p:nth-of-type(3){
    color:red;
  }
</style>
<h1>标题</h1>
<p>这是段落1</p>
<p>这是段落2</p>
<span>这是span1</span>
<span>这是span2</span>
<span>这是span3</span>
<p>这是段落3</p>
复制代码
效果以下:
复制代码


这个也不难理解就是按照类型来计算,碰到一个同类型就加1,直到遇到所设定的元素就添加相应样式:spa

.item:nth-of-type{color:red}复制代码

那么直接在class后面:nth-of-type呢?code

<style>
  .item:nth-of-type(3){
    color:red;
  }
</style>
<h1>标题</h1>
<p class="item">这是段落1</p>
<p>这是段落2</p>
<span>这是span1</span>
<span class="item">这是span2</span>
<span class="item">这是span3</span>
<p class="item">这是段落3</p>
<p class="item">这是段落4</p>
<p class="item">这是段落5</p>
复制代码

效果以下:cdn


总结

  • nth-child
    按照个数来算。blog

  • nth-of-type
    按照类型来计算,同类型不断加1,直达找到累计的第几个string

相关文章
相关标签/搜索