CSS:一类孩子的第一个孩子
问题描述:
我有以下HTML:CSS:一类孩子的第一个孩子
<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>
我申请一些CSS样式,并在他们中间,我有这样的:
.article .statistics span.note {
margin-left:0px;
margin-right:5px;
}
.article .statistics span.note:first-child {
margin-left:25px;
}
第一CSS块正确应用,所有“音符”跨度之间的空间大约是5px,但我想在第一个跨度上留下一个边距,“25px”的“音符”类,但是,第一个孩子似乎并没有选择奇怪的元素,因为我也有这个CSS:
.article .statistics span {
margin-left:25px;
margin-right:5px;
}
.article .statistics span:first-child {
margin-left:0px;
}
在这里,它工作正常,除第一个以外,所有跨度都是25px(左边)。我想这跟班上的事情有关,但我看了一下互联网,这似乎是正确的语法。
感谢
答
第一span.note
不是t他的第一个孩子.statistics
,所以span.note:first-child
不匹配。第一个孩子是span
即并不是有.note
类,所以只有span:first-child
选择器没有类将匹配该子元素。
使用的技术描述here,应用左旁所有span.note
儿童,然后从后面的人单独删除它,而不是试图将它应用于第一个:
.article .statistics span.note {
margin-left:25px;
margin-right:5px;
}
.article .statistics span.note ~ span.note {
margin-left:0px;
}
答
尝试很重要的这个属性
.article .statistics span:first-child {
margin-left:0px !important;
}
答
你可以直接匹配第一个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;
}
Codepen例子:http://codepen.io/anon/pen/WvdqbR
答
你似乎并不了解:first-child
。所有这个选择器要求是“我是我父母的第一个孩子吗?” - 没有更多。你们没有一个能够完成这个。
.article .statistics span:first-child { margin-left:0px; }这将删除您的25px保证金 –
嗨,我不明白为什么......但是,我删除它(实际上它看起来更好没有),我仍然有问题。这个选择器是div的第一个跨度,我想要的是第一个跨度为“class”的选择器。 – ssougnez
所以你想要19/06/2015跨度是25px左而不是0px? –