选择第n个元素,除非元素位于特定位置,而last-child使用CSS

时间:2016-12-20 07:52:34

标签: css css-selectors

我想从第4个开始用一个选择器选择所有元素。但我不想选择第4个,如果它是最后一个元素。

.container div {
    display: inline-block;
    margin: 5px;
}

.container div:nth-child(n+4):not(:nth-child(4):last-child) {
    background: red;
}
<div class="container">
<div>1</div>
<div>2</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>

的jsfiddle: https://jsfiddle.net/e9fgdeu1/

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
.container div {
display: inline-block;
margin: 5px;
}

.container div:nth-child(n+4) {
background: red;
}

.container div:nth-child(4):last-child {
background: none;
}
&#13;
<div class="container">
<div>1</div>
<div>2</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

我认为只有一个选择器不足以得到它。但是可以使用以下选择器完成:

.container div:nth-child(n + 5),
.container div:nth-child(4):not(:last-child) {
  background: red;
}

&#13;
&#13;
.container div {
  display: inline-block;
  margin: 5px;
}

.container div:nth-child(n + 5),
.container div:nth-child(4):not(:last-child) {
  background: red;
}
&#13;
<div class="container">
  <div>1</div>
  <div>2</div>
</div>
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
</div>
&#13;
&#13;
&#13;