CSS如何申请:第一个孩子和最后一个孩子

问题描述:

我有一个问题,使用CSS :first-child:last-childCSS如何申请:第一个孩子和最后一个孩子

我需要在标签<a>之间为第一个标签添加一些空格,我只需要margin-bottom:5px和为最后一个标签0px。

在这里我的代码..我在这里做错了吗?任何其他的选择?由于

.addthis_toolbox.atfixed 
    { 
     border: 1px solid #eee; 
     padding: 5px; 
     width: 32px; 
    } 
    .addthis_toolbox:first-child 
    { 
     margin-bottom:5px; 
    } 
    .addthis_toolbox:last-child 
    { 
    margin-bottom:0px; 
    } 

<!-- AddThis Button BEGIN --> 
<div class="addthis_toolbox addthis_32x32_style atfixed"> 
    <a class="addthis_button_preferred_1"></a> 
    <a class="addthis_button_preferred_2"></a> 
    <a class="addthis_button_preferred_3"></a> 
    <a class="addthis_button_preferred_4"></a> 
    <a class="addthis_button_compact"></a> 
</div> 
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e55018a5d405a71"></script> 
<!-- AddThis Button END --> 

直接固定你提供什么,你需要:

.addthis_toolbox a:first-child 
{ 
    margin-bottom:5px; 
} 
.addthis_toolbox a:last-child 
{ 
margin-bottom:0px; 
} 

的问题.addthis_toolbox:first-child是,它选择一个.addthis_toolbox是其父的第一个孩子。这不是你想要的。


我可能会得到这里混淆,但如果你想添加之间的间隙的各个a,使用它来处理:

.addthis_toolbox a + a { 
    margin-top: 5px; 
} 

它的整洁和有更好的浏览器支持由于未使用:last-child

您需要.addthis_toolbox:first-child/:last-child

之间添加一个空格,否则,它只会选择.addthis_toolbox元素是父母的第一个或最后一个孩子。

:first-child被施加到元件,则选择仅元件其中元素的其父的first-child

您可以阅读关于伪选择器在w3c spec中的工作方式的更多信息。