第n个类型的工作方式与第n个孩子一样,我无法在非常简单的标记中选择想要的内容

时间:2019-05-30 04:27:50

标签: html css

请参阅此代码笔或以下屏幕截图和代码:https://codepen.io/rockmandash/pen/YbJQqG

我的HTML

<div class="container">
  <div class="child"></div>
  <div class="line"></div>
  <div class="child"></div>
  <div class="line"></div> I want to select this element(second line)
  <div class="child"></div>
  <div class="line"></div>
</div>

CSS

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}
.line:nth-of-type(2) {  I chosed, but not working as expected
  width: 15px;
  height: 15px;
  background: black;
}

屏幕截图

enter image description here

为什么我的nth-of类型像nth-child一样工作?

2 个答案:

答案 0 :(得分:3)

:nth-of-type 与给定类型(例如nth)的<div>兄弟姐妹匹配。

由于.line元素是<div>元素,因此,.line:nth-of-type(2)实际上是要指定第二个具有相同 type 兄弟元素的兄弟元素>为.line

div
    div
    div - target
    div
    div

这是第一 .line

您可能想要的是.line:nth-of-type(4),或者更容易混淆的是div:nth-of-type(4)

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(4) {
  width: 15px;
  height: 15px;
  background: black;
}
<div class="container">
  <div class="child"></div>
  <div class="line"></div>
  <div class="child"></div>
  <div class="line"></div> I want to select this element(second line)
  <div class="child"></div>
  <div class="line"></div>
</div>

请注意,没有:nth-of-class这样的东西,因此,如果您不想使用这种复杂的选择器,则可能需要为元素分配唯一的类或ID。

答案 1 :(得分:1)

:nth-of-type(n)选择器匹配其父级的第n个子元素(具有特定类型(如div and p)的每个元素,而:nth-child(n)选择器匹配子元素的第n个子元素,而不管其父项的类型如何。

因此,nth-child使用div或span而不是line class

.container {
  border: 1px solid red;
  width: 50px;
  height: 150px;
}

.child {
  width: 30px;
  height: 30px;
  background: green;
  margin: 6px;
}

.line:nth-of-type(2) {
  width: 15px;
  height: 15px;
  background: black;
  display:block;
}
<div class="container">
  <div class="child"></div>
  <span class="line"></span>
  <div class="child"></div>
  <span class="line"></span> 
  <div class="child"></div>
  <span class="line"></span>
</div>