csscss-selectors

nth-child odd and even working on main element rather than class


My code:

.project-gallery .portrait:nth-child(odd) { padding-left: 0 !important; }
.project-gallery .portrait:nth-child(even) { padding-right: 0 !important; }
<div class="project-gallery">
  <a class="fancybox landscape">A</a>
  <a class="fancybox portrait">B</a>
  <a class="fancybox portrait">C</a>
  <a class="fancybox landscape">D</a>
</div>

I have also tried nth-of-type ... no luck.

But this only targets the a element - so B ends up using even and C using odd. Why can I not just target the class and that nth-child? How can I rewrite this CSS rule to do that?


Solution

  • Use the 'of' extension see https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

    :nth-child(odd of .portrait)
    :nth-child(even of .portrait)
    

    Here's an example:

    :nth-child(odd of .portrait) {
      color: red;
    }
    
    :nth-child(even of .portrait) {
      color: blue;
    }
    <div class="project-gallery">
      <a class="fancybox landscape">A</a>
      <a class="fancybox portrait">B</a>
      <a class="fancybox portrait">C</a>
      <a class="fancybox landscape">D</a>
    </div>