第一个子元素的css选择器

Vic*_*Vic 0 html css css-selectors

假设我的html看起来像这样:

<div class="container">
    <... some html here ...>
</div>
Run Code Online (Sandbox Code Playgroud)

我想得到第一个直接的孩子.container.

我能做到.container > div:first-child但是假设它是一个div并非总是如此.

Sam*_*son 7

使用:first-child不带标记名的伪类:

.container > :first-child
Run Code Online (Sandbox Code Playgroud)

这将抓取任何直接第一个子元素,无论其标记名如何.这类似于我们使用其他伪类的方式,例如:hover单独定位任何元素,而a:hover仅定位锚点的悬停状态.