css apply styling to all elements except those in the last row

被刻印的时光 ゝ 提交于 2019-12-06 08:51:48

问题


I have a product category page with 3 products per row. I want every row to have a border bottom except for the last row. This should have no border bottom. The last row may contain 1, 2, or 3 <li> elements.

The current code that I'm using applies the border-bottom property to every 3rd <li> element, which is not quite what I want.

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>

回答1:


I think I figured this out. The second ruleset below accounts for any amount of products on the last row.

.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/

A better fiddle, adjusting the display as asked, and showing the three use cases

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




回答2:


This should do the trick: (Tested on FF 33)

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

Here's a Fiddle


This is a great website for testing nth-child stuff.


EDIT:

Your situation is quite tricky and I think it's not possible only using CSS.

I made a working JSBin, which uses JavaScript to achieve your desired result.

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');
}


来源:https://stackoverflow.com/questions/26563385/css-apply-styling-to-all-elements-except-those-in-the-last-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!