This question already has an answer here:
- CSS3 selector :first-of-type with class name? 8 answers
- css3 nth of type restricted to class [duplicate] 2 answers
I am working on a simple HTML for an image gallery. Each row of the gallery can have 2, 3 or 4 images. (In an 2-image row, each image element is named type-2
, the same goes to type-3
and type-4
.)
Now I want to select the last element of each row to set a custom margin. My HTML is like this:
<div id="content">
<div class="type-2"></div>
<div class="type-2"></div> <!-- I want this, 2n+0 of type-2 -->
<div class="type-3"></div>
<div class="type-3"></div>
<div class="type-3"></div> <!-- this, 3n+0 of type-3 -->
<div class="type-4"></div>
<div class="type-4"></div>
<div class="type-4"></div>
<div class="type-4"></div> <!-- this, 4n+0 of type-4 -->
<div class="type-2"></div>
<div class="type-2"></div> <!-- this -->
<div class="type-3"></div>
<div class="type-3"></div>
<div class="type-3"></div> <!-- this -->
<div class="type-4"></div>
<div class="type-4"></div>
<div class="type-4"></div>
<div class="type-4"></div> <!-- this -->
</div>
I think the following CSS would work but it didn't:
.type-2:nth-of-type(2n+0) {margin-right:0;}
.type-3:nth-of-type(3n+0) {margin-right:0;}
.type-4:nth-of-type(4n+0) {margin-right:0;}
What this CSS selects is:
<div id="content">
<div class="type-2"></div>
<div class="type-2"></div> <!-- selected by .type-2:nth-of-type(2n+0) -->
<div class="type-3"></div> <!-- selected by .type-3:nth-of-type(3n+0) -->
<div class="type-3"></div>
<div class="type-3"></div>
<div class="type-4"></div>
<div class="type-4"></div>
<div class="type-4"></div> <!-- selected by .type-4:nth-of-type(4n+0) -->
<div class="type-4"></div>
<div class="type-2"></div> <!-- selected by .type-2:nth-of-type(2n+0) -->
<div class="type-2"></div>
<div class="type-3"></div> <!-- selected by .type-3:nth-of-type(3n+0) -->
<div class="type-3"></div>
<div class="type-3"></div>
<div class="type-4"></div>
<div class="type-4"></div> <!-- selected by .type-4:nth-of-type(4n+0) -->
<div class="type-4"></div>
<div class="type-4"></div>
</div>
I can edit my HTML to achieve what I want, but just out of curiosity, is there some kind of CSS for this?
Edit: this question may look like a duplicate of questions asking if nth-child
and nth-of-type
can be applied to classes -- not elements. I already knew the answer is no. What I'm really asking for is a pure CSS solution/hack for it, and the chosen answer did just that.