如何在CSS中引用给定选择器的第一个出现?

时间:2023-01-03 20:31:18

HTML:

<div class="foo">firstBar</div><!-- give this one a different style -->
<div class="foo">secondBar</div>
<div class="foo">thirdBar</div>

CSS:

 .foo { font-size: 12pt }

Without editing the existing HTML, is it possible to somehow reference the first occurence of the class "foo" and give it a different style?

如果不编辑现有的HTML,是否有可能以某种方式引用类“foo”的第一次出现并赋予它不同的风格?

3 个解决方案

#1


div:first-child { font-size: 12pt }

Note: For :first-child to work in IE a DOCTYPE must be declared. This won't work in IE6.

注意:对于:在IE中工作的第一个孩子,必须声明DOCTYPE。这在IE6中不起作用。

#2


If the elements succeed each other, you can use this:

如果元素相互成功,您可以使用:

.foo { font-size: 2em }
.foo + .foo { font-size: inherit }

#3


If the divs are contained in an outer div and the first foo was the first child of this outer div, you could use div#outer_div + div.foo { font-size: 12pt }

如果div包含在外部div中,并且第一个foo是此外部div的第一个子节点,则可以使用div#outer_div + div.foo {font-size:12pt}

EDIT: Commenter is right, this wouldn't work. The way to do it with + would be to reset the font-size attribute for all the other div.foo's, ad infinitum:

编辑:评论者是对的,这是行不通的。使用+来实现它的方法是重置所有其他div.foo的font-size属性,无限制:

div.foo + div.foo { ... } div.foo + div.foo + div.foo { ... }

div.foo + div.foo {...} div.foo + div.foo + div.foo {...}

This wouldn't be a good way to go about it, so disregard my answer.

这不是一个很好的方法,所以忽略我的答案。

#1


div:first-child { font-size: 12pt }

Note: For :first-child to work in IE a DOCTYPE must be declared. This won't work in IE6.

注意:对于:在IE中工作的第一个孩子,必须声明DOCTYPE。这在IE6中不起作用。

#2


If the elements succeed each other, you can use this:

如果元素相互成功,您可以使用:

.foo { font-size: 2em }
.foo + .foo { font-size: inherit }

#3


If the divs are contained in an outer div and the first foo was the first child of this outer div, you could use div#outer_div + div.foo { font-size: 12pt }

如果div包含在外部div中,并且第一个foo是此外部div的第一个子节点,则可以使用div#outer_div + div.foo {font-size:12pt}

EDIT: Commenter is right, this wouldn't work. The way to do it with + would be to reset the font-size attribute for all the other div.foo's, ad infinitum:

编辑:评论者是对的,这是行不通的。使用+来实现它的方法是重置所有其他div.foo的font-size属性,无限制:

div.foo + div.foo { ... } div.foo + div.foo + div.foo { ... }

div.foo + div.foo {...} div.foo + div.foo + div.foo {...}

This wouldn't be a good way to go about it, so disregard my answer.

这不是一个很好的方法,所以忽略我的答案。