繁体   English   中英

CSS如何应用:first-child和:last-child

[英]CSS how to apply :first-child and :last-child

我在使用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 -->

您需要在.addthis_toolbox:first-child / :last-child之间添加一个空格

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

:first-child应用于元素, 选择元素其父元素的first-child的元素。

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

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

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

暂无
暂无

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

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