4

here's the case:

https://jsfiddle.net/rpepf9xs/

I want to remove the border-bottom with selector: "nth-last-child()", however, if there are only 8 "li" in list, it goes wrong like this:

ul {
  display: block;
  width: 100%;
  margin: 0;
  padding: 0
}
li {
  display: block;
  width: 33%;
  height: 120px;
  float: left;
  margin: 0;
  padding: 0;
  border-bottom: #666 1px solid;
  background: #fcc
}
li:nth-last-child(3),
li:nth-last-child(2),
li:last-child {
  border-bottom: 0px
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

Is there any way to fix this without javascript?

Thanks.

jafarbtech
  • 6,842
  • 1
  • 36
  • 55
Wesleywai
  • 195
  • 11

3 Answers3

2

add clear:both only 3n+1 element from the forth element. remove border for the li that is after the forth element from last

ul {
  display: block;
  width: 100%;
  margin: 0;
  padding: 0
}
li {
  display: block;
  width: 33%;
  height: 120px;
  float: left;
  margin: 0;
  padding: 0;
  border-bottom: #666 1px solid;
  background: #fcc
}
li:nth-child(3n+1) {
  clear:both;
}
li:nth-last-child(4) ~ li:nth-child(3n+1), li:nth-last-child(4) ~ li:nth-child(3n+1) ~ li {
  border-bottom: 0px;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

This code will remove last row's border bottom no matter how many li you have

Explaination:-

li:nth-last-child(4) will be the forth element from last(border removal should start after this element).

So starting from li:nth-last-child(4) element we travel towards the li:nth-child(3n+1) element (which series like 4,7,10...) and the border should not be there starts from this (li:nth-child(3n+1)) element. ~ is the successor siblings selector.

jafarbtech
  • 6,842
  • 1
  • 36
  • 55
  • Would you please explain how this selector works? "li:nth-last-child(4) ~ li:nth-child(3n+1){ }" – Wesleywai Nov 16 '16 at 09:25
  • why complex code when issue can be solved with one clear. no matter how many li you have it will always give the same result. – Leo the lion Nov 16 '16 at 09:35
  • Wesleywai : I have added the explanation. @Leothelion it will work even for any number of elements. it will also be helpful for some other in our community – jafarbtech Nov 16 '16 at 09:49
  • @jafarbtech but my question is why to write that much code while we can simply do it, add clear:both after floated element(s). No need to add that much selector. got my point? – Leo the lion Nov 16 '16 at 09:51
  • @Leothelion he wants "no border-bottom on the last row" so i have explained the way to do it even if he is going dynamic. simple – jafarbtech Nov 16 '16 at 09:56