为什么我的最后一个跨度打破了我的风格?

时间:2015-01-07 10:50:40

标签: html css css-selectors

我在每个列表项之后添加,但最后一项除外。这工作得很好,直到我在末尾添加了一个跨度<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;    
}

3 个答案:

答案 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选择器。

&#13;
&#13;
.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;
&#13;
&#13;

:last-of-type适用于此选择器选择特定类型的最后一个元素(例如span)。

答案 2 :(得分:2)

您正在使用after并使用not上一个span没有符号,但您要排除最后两个span所以:

&#13;
&#13;
.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;
&#13;
&#13;