在CSS中选择直接子元素和第一个子元素

5

I have an html setup like this:

<div class = "myClass">

     <div>
         <a>Content</a>
         <p><a>Content</a></p>  
     </div>


     <p><a>Content to CHANGE!</a></p>
     <p>Content</p>

</div>

我只想给标记为“Content to Change”的元素添加10px的margin-top。我相信这个<p>class="myClass"的直接子元素,并且它是第一个<p>
然而,这个CSS样式并没有生效:
.myClass p:nth-child(1) {
    margin-top: 10px;
}

或者

.myClass > p:nth-child(1) {
    margin-top: 10px;
}

有人看出问题所在吗?


4
我认为“第一个孩子”指的是第一个孩子,而不是特定标签名称下的第一个孩子。 - Mike Christensen
1个回答

7

因为p不是.myClass的第一个子元素,而<div>是。应该使用:

.myClass p:first-of-type

您可能也想使用:

.myClass > p:first-of-type

需要显式地选择子元素。


作为额外信息,:first-of-type 在大多数浏览器中都兼容,包括IE9+ - http://caniuse.com/#search=first-of-type 对于旧版IE,您可以使用条件注释,并使用jQuery进行操作。CSS将是.myClass p:first-of-type, .myClass p.firstOfType,而jQ则是$('.myClass').find('> p').eq(0).addClass('firstOfType') - RaphaelDDL
2
只有第二个选择器 .myClass > p:first-of-type 能够达到效果。第一个选择器 .myClass p:first-of-type 也会选择内部 div 中的 p 元素。两者在这里都有演示:http://jsfiddle.net/HDkBS/ - GolezTrol
嘿,成功了,谢谢!另外,如果我想尝试 second-of-type,这可行吗?编辑:或者这就是 nth-of-type 的作用? - TheLettuceMaster
3
好的,我会尽力为您翻译。只有:first-of-type:last-of-type,但有:nth-of-type - Explosion Pills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接