我正在为图片库制作一个简单的 HTML。图库的每一行可以有 2、3 或 4 张图像。(在 2 图像行中,每个图像元素都命名为type-2
,type-3
和也是如此type-4
。)
现在我想选择每行的最后一个元素来设置自定义边距。我的 HTML 是这样的:
<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>
我认为下面的 CSS 会起作用,但它没有:
.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;}
这个 CSS 选择的是:
<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>
我可以编辑我的 HTML 来实现我想要的,但出于好奇,是否有某种 CSS 用于此目的?
编辑:这个问题可能看起来像询问是否nth-child
并且nth-of-type
可以应用于类的问题的重复 - 而不是元素。我已经知道答案是否定的。我真正想要的是一个纯 CSS 解决方案/hack,而选择的答案就是这样做的。