我找不到正确的 CSS 选择器,我的结构如下所示:
<div>
<a href="#"></a>
</div>
<div>
<a href="#"></a>
</div>
<div>
<a href="#"></a>
</div>
我想为第一个 div
的 a
元素设置样式
我试过这个选择器但没有成功
div:first-child a{}
最佳答案
first-child
应该很好用,你可以试试
div:nth-of-type(1) a { /* Or div:first-child a */
color: red;
}
上面的选择器将选择所有第一个 div
元素并将颜色应用于第一个 div
内的所有 a
如果您愿意在每个 div
标签中为第一次出现的 a
设置样式,那么您需要使用
div a:nth-of-type(1) { /* Or div a:first-child */
color: red;
}
这里每第一个 a
将在每个 div
标签中被选中
最后但并非最不重要的一点是,如果你只想在第一个 div
中选择第一个 a
而不是使用下面的选择器
div:nth-of-type(1) a:nth-of-type(1) { /* Or div:first-child a:first-child */
color: red;
}
Note: If still the above selectors doesn't work, than the possibility is either some rule is more specific than the rules you are declaring, or
!important
is used somewhere, or (least chances) you are testing on older browsers
关于CSS 选择器 : Style the first "a" inside a div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012021/