【发布时间】:2018-03-20 03:08:26
【问题描述】:
例如,我有类似的 HTML:
<div class='page'>
<span>2</span>
<span>2</span>
<a>1</a>
<a>6</a>
</div>
如何为第一个孩子设置样式
我是这样使用的:.page a:first-child {color:red}
但它没有运行。
【问题讨论】:
标签: html css css-selectors
例如,我有类似的 HTML:
<div class='page'>
<span>2</span>
<span>2</span>
<a>1</a>
<a>6</a>
</div>
如何为第一个孩子设置样式
我是这样使用的:.page a:first-child {color:red}
但它没有运行。
【问题讨论】:
标签: html css css-selectors
使用 first-of-type 代替 first-child
.page a:first-of-type{
color:red;
}
:first-of-type CSS 伪类表示其父元素的子元素列表中其类型的第一个兄弟。
取自MDN Documentation。您可以找到更多详细信息和示例here.
【讨论】:
正如 Pranav c 所说,您可以使用
.page a:first-of-type { ... } 或 .page a:nth-of-type(1) { ... } 但它们都不能在 IE8
因此,如果我们可以假设<span> 始终存在,那么
.page span+a { ... }
将确保仅设置跨度后的第一个 a 样式,这与您现在可以跨浏览器一样好。
示例:FIDDLE
【讨论】: