首页 > 解决方案 > 当第一个在“div”内时,为什么“first-child”伪类不能处理 table-row (tr) 元素?

问题描述

tr:first-child {
    background-color:lime;
}
<table>

    <div>
        <tr>
            <th>Something</th>
        </tr>
    </div>

    <tr>
        <td>Something Something</td>
        <td>Something Something</td>
    </tr>

    <tr>
        <td>Something Something</td>
        <td>Something Something</td>
    </tr>

    <tr>
        <td>Something Something</td>
        <td>Something Something</td>
    </tr>

</table>

我使用“div”作为第一个“tr”的父容器。所以在这种情况下,'first-child' 应该适用于“div”容器的“tr”,以及“table”父级的第一个“tr”,但 first-child 只适用于第一个“tr”在 div 容器内。为什么?

first-child 应该应用于父容器的第一个子元素。父容器的第一个子元素是第 th 元素,table-parent 的第一个子元素是第一个 td 元素。

似乎表格标签结构在这里搞砸了,但我不知道到底是怎么回事。

笔记:

是的,我知道表结构无效,但这对于子元素伪类的工作方式无关紧要。

这是另一个使用“div”容器的示例。

<div>

<p>first paragrapth</p>

<div>

    <p>First paragrapth of the div container</p>

</div>


</div>

CSS:

p:first-child {
    background-color:red;
    }

这个例子本质上是一样的,只是我没有使用“table”,而是使用了“div”。为什么第一个子伪类在这种情况下以应有的方式工作,而不是“表”示例?仅仅是因为“表”中“div”的使用弄乱了表标记结构,导致伪类无法将其他“表行”识别为表父的第一个子元素吗?

标签: htmlcss

解决方案


选择器:first-child会像您所说的那样在父级中查找第一个元素,在这种情况下tr。例如,如果我希望第一段具有background-color: yellow.

p:first-child {
  background-color: yellow;
}
<div>
<p>This paragraph is the first child inside of a div.</p>
</div>

<p>This paragraph is the second child.</p>
<p>This paragraph is the third child.</p>

但是,在您的代码中,第一个tr是 div 中的第一个孩子,也是表中的第一个孩子。因此只tr选择第一个


推荐阅读