CSS如何申请:first-child和:last-child

时间:2011-08-24 16:26:27

标签: html css addthis

我在使用CSS :first-child:last-child时遇到问题。

我需要在标记<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 -->

2 个答案:

答案 0 :(得分:4)

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

之间添加空格

否则,它只会选择.addthis_toolbox元素作为父母的第一个或最后一个孩子。

:first-child应用于该元素,选择元素,其中元素 其父级的first-child

您可以阅读有关伪选择器如何在w3c spec中工作的更多信息。

答案 1 :(得分:3)

直接修复您提供的内容,您需要:

.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,它更整洁,浏览器支持更好。

相关问题