选择第一个子元素而不知道第一个子元素的类型

7
我有以下 HTML 代码:

<div class="foo">
   ...
   <span> ---> can be the first
   <h1> ---> can be the first
   <h2> ---> can be the first
   and so on...
   ...
</div> 

我希望为第一个元素添加一些CSS样式,但不声明HTML元素的类型。
例如,下面的代码将无法帮助我:
.foo span:first-child

我希望能够创建适用于第一个元素的CSS,即使开发人员选择在该div内进行更改也能生效。
有没有办法实现这个目标?

3
.foo > *:first-child? - putvande
.foo :nth-child(1) 是另一种选项。 - Alex
@Alex 如果你不需要支持IE8的话,可以考虑使用.foo > :nth-child(1) - Hashem Qolami
是的,我忘记了一个空格,我的错。不知道IE8支持,但感谢您提供的信息。 - Alex
感谢 @putvande - 那个很好用! - mashiah
你也可以像这样使用逗号: .foo > div:first-child, .foo > h1:first-child, .foo > h2:first-child {...}。但这并没有回答你的问题。 - Bas
5个回答

9

您可以添加以下CSS代码,它将针对任何作为.foo的第一个子元素的元素。

.foo > :first-child {
    /* styling here */
}

2
* 可以省略。 - Hashem Qolami
1
以下是有关编程的内容,需要将其翻译成中文。 - Avinash Babu
本来想发布这个小例子,但是你比我更快^^。http://jsfiddle.net/Bladepianist/bjv7er5v/ 编辑:从我的小例子中删除了* - Bladepianist
不想打击大家的兴致,但我们真的应该尽量节省服务器空间,避免使用JSFiddle或其他平台来编辑这些小代码块...仅代表个人意见。 - Alex
我怀疑它并没有使用太多的空间 @Alex - putvande

2

是的,有许多实现这一目标的方法:

.foo > :first-child {
    /* Your Styles */
}

.foo > :first-of-type {
    /* Your Styles */
}

.foo > :nth-child(1) {
   /* Your Styles */
}

1
.foo>*:first-child {
    /*style here*/
}

1

.foo > *:first-child
{
  color:green;
}
<div class="foo">
   ...
  <h2> ---> can be the first another</h2>
   <span> ---> can be the first</span>
  
   <h1> ---> can be the first</h1>
   
   and so on...
   ...
</div> 


0

CSS 2.1 将 选择器语法 定义如下:

一个 简单选择器 要么是 类型选择器,要么是通用选择器,后面紧跟着零个或多个属性选择器ID 选择器伪类选择器,顺序任意。[...]

选择器 是由一个或多个简单选择器链式组合而成的。组合器有:空格、">" 和 "+".

注意:CSS3中的术语略有不同。

因此,您的简单选择器必须始终以类型选择器或通用选择器开头。当您不知道要匹配的元素类型时,请使用通用选择器

通用选择器“*”匹配任何元素类型的名称。它匹配文档树中的任何单个元素。

但是,在这种情况下,通用选择器不是唯一的组件,还有:first-child伪类。因此,您可以省略*

如果通用选择器不是简单选择器的唯一组成部分,则可以省略“*”。

因此,该简单选择器将是以下之一(它们是等效的):

:first-child

*:first-child

完整的选择器将是

.foo :first-child

.foo *:first-child

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接