【问题标题】:css apply styling to all elements except those in the last rowcss 将样式应用于除最后一行之外的所有元素
【发布时间】:2014-12-21 04:54:31
【问题描述】:

我有一个产品类别页面,每行包含 3 个产品。我希望每一行的最后一行都有一个边框底部 except。这应该没有边框底部。最后一行可能包含 1、2 或 3 个<li> 元素。

我正在使用的当前代码将border-bottom 属性应用于每个第三个<li> 元素,这不是我想要的。

CSS:

.products li {
    width: 33.33333%;
}

.products li:nth-child(3n){
    border-bottom: 1px rgba(51, 51, 51, 0.1) solid;
}

.products li:nth-child(2-PREVIOUS-SIBLING-ELEMENTS){
    border-bottom: 1px rgba(51, 51, 51, 0.1) solid;
}

HTML:

<ul class="products">
   <li>Product</li>
   <li>Product</li>
   <li>Product</li>
   <li>Product</li>
   <li>Product</li>
   <li>Product</li>
</ul>

【问题讨论】:

    标签: css css-selectors pseudo-element pseudo-class


    【解决方案1】:

    这应该可以解决问题:(在 FF 33 上测试)

    .products li:nth-last-child(-n+3) {
        border-bottom: none;
    }
    

    这是Fiddle


    This 是一个很棒的网站,用于测试 nth-child 东西。


    编辑:

    您的情况很棘手,我认为仅使用 CSS 是不可能的。

    我做了一个工作JSBin,它使用JavaScript来实现你想要的结果。

    HTML

    <ul class="products">
     <li>Product</li>
     <li>Product</li>
     <li>Product</li>
     <li>Product</li>
     <li>Product</li> 
     <li>Product</li>
     <li>Product</li>
     <li>Product</li>
     <li>Product</li>
     <!-- more products -->
    </ul>
    

    CSS

    .products li {
        width: 30.33333%;
        border-bottom: 1px solid red;
    }
    

    JS

    var size = $('.products li').size();
    
    var previous = Math.floor((size)/3)*3;
    if (size % 3 === 0 ) {
      previous = size - 3;
    }
    
    for (var i = previous; i < size; i++ ) {
    
        $('.products li:eq(' + i + ')').css( 'border-bottom' , 'none');
    }
    

    【讨论】:

    • 此方案仅在最后一行有 1 个
    • 时有效。如果最后一行有 2 或 3 个
    • 元素,您的解决方案将简单地从最后的
    • 元素中删除“border-bottom”,而不是最后的 2 或 3 个
    • 元素
  • 新代码是否符合您的要求?也许你必须使用 nth-last-child(-n+4)
  • 没有。因为我们不知道最后一行会有多少项目。可能有 1、2 或 3 个
  • 对不起,我不明白结果应该是什么样子。您能否在您的问题中添加图像或其他内容,以显示您想要的结果。这对我有很大帮助。 nth-last-child(-n+2) 也错了?
  • 请看附图
  • 【解决方案2】:

    我想我想通了。下面的第二个规则集适用于最后一行的任意数量的产品。

    .products li:nth-child(3n){
        border-bottom: 1px rgba(51, 51, 51, 0.1) solid;
    }
    
    .products li:nth-last-child(-n + 3):nth-child(3n + 1),
    .products li:nth-last-child(-n + 3):nth-child(3n + 1) ~ li {
        border: none;
    }
    

    http://jsfiddle.net/6rso3t85/

    一个更好的小提琴,按要求调整显示,并显示三个用例

    http://jsfiddle.net/6rso3t85/1/

    【讨论】:

    • 您的规则集没问题,但小提琴没有显示 OP 问题的三列。我也加了三个案例,只是为了更好的展示一下
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签