我在每个列表项之后添加•
,但最后一项除外。这工作得很好,直到我在末尾添加了一个跨度<span class="more-brands">
。现在我的上一个品牌商品也有•
。怎么会? See my fiddle
<div class="brand-list">
<span class="brand">Haaning and Htoon</span>
<span class="brand">Alexander McQueen</span>
<span class="brand">Alexander Wang</span>
+ <span class="more-brands">39</span> more brands
</div>
// All except the last span with class name 'brand'
.brand:not(:last-child):after {
content: "•";
display: inline-block;
font-size: 20px;
padding: 0 5px;
position: relative;
text-align: center;
top: 3px;
}
答案 0 :(得分:3)
不幸的是,当前的CSS没有“具有特定类的最后一个元素”的选择器。 .brand:not(:last-child)
表示“brand
类的元素不是其父级的最后一个子级”,而span
类的所有brand
都与此匹配条件。
如果您的目标是在类•
的 span
之间插入brand
个字符,那么插入它们会不合适除了第一个之外,每个span.brand
之前?
/* All spans with class name 'brand' except the first one*/
.brand + .brand:before {
content: "•";
display: inline-block;
font-size: 20px;
padding: 0 5px 0 2px;
position: relative;
text-align: center;
top: 3px;
}
<div class="brand-list">
<span class="brand">Haaning and Htoon</span>
<span class="brand">Alexander McQueen</span>
<span class="brand">Alexander Wang</span>
+ <span class="more-brands">39</span> more brands
</div>
作为奖励,这将适用于IE8(它不能识别:not()
和:nth-last-*
等CSS3选择器
答案 1 :(得分:2)
:last-child
选择父级中的最后一个孩子。父级中的最后一个子级是.more-brands
元素。您的.brand
个元素都不是:last-child
。
要解决此问题,您可以删除&#34; 39&#34;周围的span
元素,或使用其他元素并改为使用:last-of-type
选择器。
.brand:not(:last-of-type):after {
content: "•";
display: inline-block;
font-size: 20px;
padding: 0 5px;
position: relative;
text-align: center;
top: 3px;
}
&#13;
<div class="brand-list">
<span class="brand">Haaning and Htoon</span>
<span class="brand">Alexander McQueen</span>
<span class="brand">Alexander Wang</span>
+ 39 more brands
</div>
<p>Or:</p>
<div class="brand-list">
<span class="brand">Haaning and Htoon</span>
<span class="brand">Alexander McQueen</span>
<span class="brand">Alexander Wang</span>
+ <i>39</i> more brands
</div>
&#13;
:last-of-type
适用于此选择器选择特定类型的最后一个元素(例如span
)。
答案 2 :(得分:2)
您正在使用after
并使用not
上一个span
没有符号•
,但您要排除最后两个span
所以:
.brand-list {
width: 400px;
font-size: 0.9rem;
margin-top: 5px;
}
.brand {
color: #557486;
}
.brand-list span:not(:nth-last-child(-n+2)):after {
content: "•";
display: inline-block;
font-size: 20px;
padding: 0 5px;
position: relative;
text-align: center;
top: 3px;
}
&#13;
<div class="brand-list">
<span class="brand">Haaning and Htoon</span>
<span class="brand">J. Lindeberg</span>
<span class="brand">7 for all Mankind</span>
<span class="brand">Alexander McQueen</span>
<span class="brand">Alexander Wang</span> + <span class="more-brands">39</span> more brands
</div>
&#13;