我正在为一个图片库编写一个简单的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解决方案/黑客,而选择的答案就是这样。
发布于 2013-10-19 17:31:59
如果只使用CSS攻击,而不修改标记,则可以执行以下操作:
[class*=' type-'], [type^='type-']{ /* Set all the divs to float: left initially */
float: left;
content: url('http://static.adzerk.net/Advertisers/db5df4870e4e4b6cbf42727fd434701a.jpg');
height: 100px; width: 100px;
}
.type-2 + .type-2 + div{
clear: both; /* Clear float for a div which follows two div with class type-2 */
}
.type-3 + .type-3 + .type-3 + div {
clear: both; /* Clear float for a div which follows three div with class type-3 */
}
.type-4 + .type-4 + .type-4 + .type-4 + div {
clear: both; /* /* Clear float for a div which follows four div with class type-4 */
}演示Fiddle
发布于 2013-10-19 17:51:06
这是不可能的CSS选择器级别3(至少,没有CSS黑客,额外的标记,或JavaScript)。
第4级CSS选择器草案建议使用:nth-match()伪类,它可以做您想做的事情:
:nth-match(2n+0 of .type-2) {margin-right:0;}
:nth-match(3n+0 of .type-3) {margin-right:0;}
:nth-match(4n+0 of .type-4) {margin-right:0;}据我所知,这还没有被任何浏览器实现,但是有一个臭虫档案在Chrome中实现它。
发布于 2013-10-19 17:09:25
nth-child和nth-of-type是伪类,只能应用于元素。
.layout:nth-of-type是类的伪类,因此无法工作。
Jquery的情商可能提供一个解决方案
http://api.jquery.com/eq/
https://stackoverflow.com/questions/19468639
复制相似问题