wang1dot0 / personal-note

记录工作中遇到的个人觉得比较有意思的小问题
https://github.com/wang1dot0/personal-note
0 stars 0 forks source link

CSS相关 #14

Open wang1dot0 opened 5 years ago

wang1dot0 commented 5 years ago

nth-child 与 nth-of-type的区别

两者都是伪类选择器,直接看例子

<div class="container">
  <p>This is the first sentence</p>
  <p>This is the second sentence</p>
</div>

这里p::nth-child(2)p::nth-of-type(2)无差别,都是第二个p标签 但是我们变更一下

<div class="container">
  <span>This is a span.</span>
  <p>This is the first sentence</p>
  <p>This is the second sentence</p>
</div>

这里p::nth-child(2)p::nth-of-type(2)就大大的不同了,nth-child(2)会选中第一个p标签,而nth-of-type(2)依旧选择第二个p标签。 总结:

  1. nth-child表示父元素的第2个元素,并且为p标签的元素,这里就选中了第一个,注:如果第二个元素不是p标签,那么就未选中。
  2. nth-of-type表示父元素的所有p标签的子元素中第二个。
wang1dot0 commented 5 years ago

BFC (Block Formatting Context)


三种常见的定位方案