1

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

这个想法是每行有 4 个 div,我对所有 div 使用 float:left 和 clear:both 使用 :nth-child(4n+1) 选择器。一些 div 我想排在第一位(cr 之前),我用 class="cr" 标记它,但我希望它在同一行之后有 3 个 div,在 cr 之前(清除:两者)。

目标是:

Test Test
Test Test Test Test 
Test Test Test Test

是否可以 ?到目前为止,我在这里:http: //jsbin.com/isowab/1/edit

4

3 回答 3

5

据我所知,您想要做的是在纯 css 中不太可能(但我很乐意被证明是错误的)。

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

不幸的是,CSS 不能那样工作。每次您分配一个新nth规则时,它将从一开始就适用于一个类型的所有元素。使用相邻的选择器+,或者~您可以做一些魔术......例如,nth仅在第一次出现 .cr 类之后才开始使用规则应用样式

但是没有办法在nthclass 的每个 div 之后重置计数器.cr

您可以通过添加层次结构或通过使用javascript服务器端动态分配特定类来做到这一点......但不是在纯 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/

于 2013-04-02T08:16:05.917 回答
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这里使用它是因为它更简单,但是如果元素之间的间隙是一个问题,您可以浮动它们或与空格打架

于 2013-04-02T08:28:24.470 回答
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;
}

小提琴

点击这里

于 2013-04-02T07:05:26.883 回答