简体   繁体   English

CSS选择器:设置div内的第一个“a”

[英]CSS selector: Style the first “a” inside a div

I am having trouble finding the correct CSS selector, the structure I have looks like this: 我找不到正确的CSS选择器,我的结构看起来像这样:

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

I would like to style the a element of the first div 我想设计第a div a元素

I have tried with this selector but with no luck 我试过这个选择器,但没有运气

div:first-child a{}

first-child should work absolutely well, you can try first-child应该工作得很好,你可以试试

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

The above selector will select all 1st div element and will apply color to all a which are inside 1st div 上面的选择器将选择所有第一个div元素,并将颜色应用于第一个div内的所有a

Demo 演示

If you are willing to style 1st occurrence of a in every div tag than you need to use 如果你愿意在每个div标签中第一次出现a ,那么你需要使用它

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

Here every 1st a will be selected in every div tag 这里每个第a都会在每个div标签中被选中

Last but not the least if you want to select 1st a only in 1st div than use the below selector 最后但并非最不重要的是,如果你想在1st div选择1st 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 注意:如果上述选择器仍然不起作用,则可能是某些规则比您声明的规则更具体,或者!important在某处使用!important ,或者在旧版浏览器上测试(最少机会)

Your own example is working too. 你自己的例子也在起作用。

http://jsfiddle.net/7Pea3/ http://jsfiddle.net/7Pea3/

div:first-child a {
    color: #f00;
}

The first div will be selected and all a recive the color #CCC . 第一个div将被选中,所有a recive颜色#CCC I don't understand why this isn't working. 我不明白为什么这不起作用。

div:first-child a { 
    color: #CCC;
}

Else test this solution, that selects the first div and styles the first a tag in the div: 否则测试此解决方案,选择第一个div并为div中的第一个标记设置样式:

div:first-child a:first-child(1) {
    color: #CCC;
}

Else you have problems with the :first-child selector use the :nth-of-type({ number expression | odd | even }) selector. 否则你有以下问题:first-child选择器使用:nth-of-type({ number expression | odd | even })选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM