CSS:有班级的孩子的第一个孩子

sso*_*nez 3 html css css-selectors

我有以下HTML:

<div class="statistics">
    <span class="glyphicon glyphicon-calendar"></span>19/06/2015
    <span class="glyphicon glyphicon-eye-open"></span> 18 lectures
    <span class="glyphicon glyphicon-comment"></span> 1 commentaire
    <span class="glyphicon glyphicon-user"></span> Sébastien Sougnez
    <span class="glyphicon glyphicon-heart note"></span>
    <span class="glyphicon glyphicon-heart note"></span>
    <span class="glyphicon glyphicon-heart note"></span>
    <span class="glyphicon glyphicon-heart note"></span>
    <span class="glyphicon glyphicon-heart-empty note"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在应用一些CSS样式,其中,我有这个:

.article .statistics span.note {
    margin-left:0px;
    margin-right:5px;
}

.article .statistics span.note:first-child {
    margin-left:25px;
}
Run Code Online (Sandbox Code Playgroud)

第一个CSS块被正确应用,所有"note"跨度之间的空间大约是5px但是我想在第一个跨度上放置一个margin,左边是25px的"note"类,但是,第一个孩子做似乎没有选择奇怪的元素,因为我也有这个CSS:

.article .statistics span {
    margin-left:25px;
    margin-right:5px;
}

.article .statistics span:first-child {
    margin-left:0px;
}
Run Code Online (Sandbox Code Playgroud)

在这里,它工作正常,所有跨度除了第一个之外由25px(左侧)分隔.我想这与课程有关,但我查看了互联网,这似乎是正确的语法.

谢谢

Bol*_*ock 7

第一个span.note不是第一个孩子.statistics,所以span.note:first-child不匹配.第一个孩子是一个span具备.note一流的,所以只有span:first-child选择无类将匹配,即子元素.

使用此处描述的技术,将左边距应用于所有span.note子节点,然后将其从后续节点中删除,而不是尝试将其单独应用于第一个:

.article .statistics span.note {
    margin-left:25px;
    margin-right:5px;
}

.article .statistics span.note ~ span.note {
    margin-left:0px;
}
Run Code Online (Sandbox Code Playgroud)

  • 它节省了两个字节!这一定很有价值.:) (2认同)

fca*_*ran 5

你可以直接匹配第一个span.note元素,就像这样

/* when it is exactly the first child of its parent 
 * (not your specific case)
 */
span.note:first-child,  

/* when it is not the first-child, and then is 
 * preceded by another span whose class is not ".note"
 */
span:not(.note) + span.note {
    margin-left: 25px;
}
Run Code Online (Sandbox Code Playgroud)

Codepen示例:http://codepen.io/anon/pen/WvdqbR