例如,我有以下HTML代码:
<div class='page'>
<span>2</span>
<span>2</span>
<a>1</a>
<a>6</a>
</div>
我如何为第一个子元素设置样式?
我尝试使用以下代码:.page a:first-child {color:red}
但它没有生效。
例如,我有以下HTML代码:
<div class='page'>
<span>2</span>
<span>2</span>
<a>1</a>
<a>6</a>
</div>
我如何为第一个子元素设置样式?
我尝试使用以下代码:.page a:first-child {color:red}
但它没有生效。
first-of-type
代替first-child
。.page a:first-of-type{
color:red;
}
正如Pranav c所说,你可以使用.page a:first-of-type { ... }
或.page a:nth-of-type(1) { ... }
,但它们都无法在IE8中工作。
因此,如果我们可以假设<span>
始终存在,那么
.page span+a { ... }
这将确保仅对span后的第一个a元素进行样式设置,目前在跨浏览器方面这已经是最好的解决方案。
示例:FIDDLE