使用nth-child&不在css选择器中

时间:2013-04-02 06:33:27

标签: css css3 css-selectors

我尝试使用css进行构建页面布局。我希望它尽可能多地独立于内容。

我的想法是每行有4个div,我使用float:left表示所有div,使用nth-child(4n + 1)选择器表示clear:both。有些div我想成为第一个(cr之前),并且我用class =“cr”标记它,但是我希望它在同一行之后有3个div,在cr之前(clear:both)。

目标是:

Test Test
Test Test Test Test 
Test Test Test Test

有可能吗? 到目前为止我在这里: http://jsbin.com/isowab/1/edit

3 个答案:

答案 0 :(得分:5)

你想要做的是根据我的知识在纯粹的CSS中不可能实现(但我会非常乐意被证明是错误的。)

如果我理解你的话......你希望在每nth课程div之后重置.cr计数吗?

很遗憾,

CSS无法正常工作。每次您分配新的nth规则时,它将从头开始申请所有类型的元素。使用相邻的选择器+~,你可以做一些魔术......例如,只有在第一次出现.cr类后才开始使用nth规则应用样式

但在课程nth 的每个div之后无法重置.cr个计数器。

您可以通过添加层次结构或通过使用 javascript 服务器端分配特定类来动态执行此操作...但 NOT 纯粹的CSS。


编辑:例如,如果您使用的是jQuery,可以添加以下内容:

    var i=1;
    $("div").each(function(){
        if($(this).hasClass('cr') || i%5==0){
            $(this).addClass('cr');
            i=1;
        }
        i++;
    });

并在css中将clear:both;应用于.cr类。

这是jsfiddle中的这个例子:http://jsfiddle.net/MJ29T/

答案 1 :(得分:2)

为什么不让这些行显式化?类似的东西:

<强> CSS

section > div { display: inline-block; background: green; }
section > div:nth-child(even) { background: blue; }

<强> HTML

<section>
    <div>Test</div>
    <div>Test</div>
</section>
<section>
    <div>Test</div>
    <div>Test</div>
    <div>Test</div>
    <div>Test</div>
</section>
<section>
    <div>Test</div>
    <div>Test</div>
    <div>Test</div>
    <div>Test</div>
</section>

我在这里使用inline-block因为它更简单但是如果元素之间的差距是个问题,你可以浮动它们或fight the spaces

答案 2 :(得分:1)

HTML

<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>
<div>Test</div>

<强> CSS

div {
    height: 20px;
    width: 40px;
    display: block;
    background: red;
    float: left;
}
div:nth-child(4n-1){
    clear:both;
}
DIV:nth-child(2n) {
    background-color: blue;
}
DIV:nth-child(2n+1) {
    background-color: green;
}

<强> FIDDLE

click here