简体   繁体   English

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

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

I have a problem using CSS :first-child and :last-child . 我在使用CSS :first-child:last-child遇到问题。

I need add some space between tag <a> for the first tag I need only margin-bottom:5px and for the last tag 0px. 我需要在标签<a>之间添加一些空间,第一个标签只需要margin-bottom:5px,而最后一个标签则需要0px。

Here my code.. What I'm doing wrong here? 这是我的代码。我在这里做错了什么? Any other alternative? 还有其他选择吗? Thanks 谢谢

.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 -->

You need to add a space between .addthis_toolbox and :first-child / :last-child 您需要在.addthis_toolbox:first-child / :last-child之间添加一个空格

Otherwise, it'll only select .addthis_toolbox elements that are the first or last child of their parents. 否则,它将仅选择.addthis_toolbox元素作为其父母的第一个或最后一个孩子。

:first-child is applied to the element, selecting only elements where the element is the first-child of its parent. :first-child应用于元素, 选择元素其父元素的first-child的元素。

You can read more about how the pseudo-selectors work in the w3c spec . 您可以在w3c规范中阅读有关伪选择器如何工作的更多信息。

Directly fixing what you provided, you need: 直接修复您提供的内容,您需要:

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

The problem with .addthis_toolbox:first-child is that it selects a .addthis_toolbox that is the first child of its parent. .addthis_toolbox:first-child在于,它选择了.addthis_toolbox作为其父级的第一个孩子。 And that's not what you wanted. 那不是您想要的。


I might be getting confused here, but if you're trying to add a gap between every a , use this to handle it: 我在这里可能会感到困惑,但是如果您尝试在每个 a之间添加一个空格,请使用此方法来处理它:

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

It's neater and has better browser support due to not using :last-child . 由于不使用:last-child ,它更加整洁并具有更好的浏览器支持。

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

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