Search code examples
csscss-selectors

Target elements excluding certain others


I have a 2-columns table formed by a list of divs and I would like to target all the divs on the right. Using :nth-of-type(even) does not work in my case because I have some divs that span on a 100% width and so they alter the cascade order. The desired result is shown in the following picture:

enter image description here

<section class="container">
  <div>#1</div>
  <div>#2</div>
  <div class="fullWidth">#3</div>
  <div>#4</div>
  <div>#5</div>
  <div>#6</div>
  <div>#7</div>
  <div class="fullWidth">#8</div>
  <div>#9</div>
  <div>#10</div>
</section>
.container {
  width: 300px;
  height: 400px;
  margin: 20px;
  outline: 2px solid lightgrey;
  display: flex;
  flex-wrap: wrap;
}
.container > div {
  flex: 1 1 50%;
  outline: 1px solid bisque;
  background-color: #c5c8d5;
}
div.fullWidth {
  width:100%;
  flex-basis: 100%;
  background-color: lightsalmon
}

I've tried adjacent and siblings selector, plus a combination of ::not(), ::last-of-type and ::first-of-type

Thanks in advance for any help


Solution

  • You can try the new nth-child() selector by excluding the fullwidth items from the selection

    .container {
      width: 300px;
      height: 400px;
      margin: 20px;
      outline: 2px solid lightgrey;
      display: flex;
      flex-wrap: wrap;
    }
    .container > div {
      flex: 1 1 50%;
      outline: 1px solid bisque;
      background-color: #c5c8d5;
    }
    div.fullWidth {
      width:100%;
      flex-basis: 100%;
      background-color: lightsalmon
    }
    
    .container > div:nth-child(even of :not(.fullWidth)) {
      background: red;
    }
    <section class="container">
      <div>#1</div>
      <div>#2</div>
      <div class="fullWidth">#3</div>
      <div>#4</div>
      <div>#5</div>
      <div>#6</div>
      <div>#7</div>
      <div class="fullWidth">#8</div>
      <div>#9</div>
      <div>#10</div>
    </section>