在不知道第一个孩子的类型的情况下选择第一个孩子

mas*_*iah 5 html css css-selectors

我有以下HTML代码:

<div class="foo">
   ...
   <span> ---> can be the first
   <h1> ---> can be the first
   <h2> ---> can be the first
   and so on...
   ...
</div> 
Run Code Online (Sandbox Code Playgroud)

我想在第一个元素中添加一些CSS样式,但不声明HTML元素的类型.

例如,这段代码对我没有帮助:

.foo span:first-child
Run Code Online (Sandbox Code Playgroud)

即使开发人员选择在div中进行更改,我也希望CSS能够在第一个元素上运行.

有什么办法吗?

put*_*nde 7

你可以添加这个CSS,它将针对作为第一个子元素的任何元素.foo:

.foo > :first-child {
    /* styling here */
}
Run Code Online (Sandbox Code Playgroud)

  • 其中`*`也可以省略. (2认同)