html - 当第一个在“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”的使用弄乱了表标记结构,导致伪类无法将其他“表行”识别为表父的第一个子元素吗?
解决方案
选择器: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
选择第一个
推荐阅读
- django - 在模板中应用 django 查询
- c - 防止控制台窗口在 C 中调整大小/滚动 (Window.h)
- r - 处理数字列中的非数字值
- .net - 当远程数据库中不存在时如何从本地数据库中选择数据
- xamarin.android - 为什么应用程序不等待用户的回答?
- node.js - ServiceBus Node.Js SDK 在创建队列时抛出错误
- python - 如何在 Python 中绘制回归树
- datagrip - 位于表字段的灰点的含义?
- c++ - 显示数组时出现问题。一切都放在单独的行中,但不放在单独的列中?
- javascript - 你如何制作一个变量,如果点击一次并且如果再次点击你已经点击了我?