CSS 选择器 : Style the first "a" inside a div

标签 css css-selectors

我找不到正确的 CSS 选择器,我的结构如下所示:

<div>
    <a href="#"></a>
</div>
<div>
    <a href="#"></a>
</div>
<div>
    <a href="#"></a>
</div>

我想为第一个 diva 元素设置样式

我试过这个选择器但没有成功

div:first-child a{}

最佳答案

first-child 应该很好用,你可以试试

div:nth-of-type(1) a { /* Or div:first-child a */
    color: red;
}

上面的选择器将选择所有第一个 div 元素并将颜色应用于第一个 div 内的所有 a

Demo

如果您愿意在每个 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/

相关文章:

html - float :left insive li in Chrome

html - 英雄单位显示不正确

CSS:如何定位表格内的特定单元格?

css - :after and :before pseudo-element selectors in Sass

javascript - 获取特定元素的 xpath 和 css 选择器的最佳方法

javascript - 使用javascript隐藏和显示下拉菜单

javascript - 目标.class :after:hover in jQuery

javascript - 在 jQuery 对话框中使用响应式 iframe

html - 嵌套类的 CSS 选择器

html - Bootstrap 4 - 内联表单上的全宽表单字段