繁体   English   中英

在div中连续填充div(css)

[英]fill the div with divs in a row (css)

我有固定大小为600px的div容器。 我想在一行中填充一些div (数字是动态值)

像这样:

|---------------------------container-------------------------|
|----box1----||----box2-----||-----box3-----||------box4------|

所有盒子的尺寸必须相同

基于表格布局的答案(纯CSS)http : //jsfiddle.net/QheN7/1/

HTML:

<div class="container">
    <div class="child">&nbsp;</div>
    <div class="child">&nbsp;</div>
    <div class="child">&nbsp;</div>
    <div class="child">&nbsp;</div>
    <div class="child">&nbsp;</div>
    <div class="child">&nbsp;</div>
</div>
<button>Add div</button>

CSS:

.container{
    display:table;
    border:1px solid #000;
    width:600px;
    height:20px;
}

.child{
    display:table-cell;
    height:20px;
}

.child:nth-child(odd){
    background-color:#aaa;
}

.child:nth-child(even){
    background-color:#666;
}

我仅将JS用于添加更多div,否则不需要:

$('button').on('click', function(){
    var newChild = $('.container').find('.child').first();
    newChild.clone().appendTo($('.container'));
});

我不确定这是否是您想要的。虽然您将需要javascript(我知道您没有在这里标记它): http : //jsfiddle.net/QheN7/

屏幕截图:

在此处输入图片说明

CSS:

.container{
    overflow:auto;
    border:1px solid #000;
    width:600px;
}

.child{
    float:left;
    height:20px;
}

.child:nth-child(odd){
    background-color:#aaa;
}

.child:nth-child(even){
    background-color:#666;
}

HTML:

<div class="container">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>
<button>Add div</button>

JS:

$(function(){
    function setWidth(){
        var container = $('.container'),
            children = $('.child'),
            containerWidth = container.width(),
            noOfChildren = children.length;
        children.width(containerWidth/noOfChildren);
    }
    $('button').on('click', function(){
        var newChild = $('.container').find('.child').first();
        newChild.clone().appendTo($('.container'));
        setWidth();
    });
    setWidth();
});

使用纯CSS实际上可以解决此问题,但并非在所有浏览器中都有效。 您的问题有点与重复。 这个想法是根据div的数量设置div的宽度。

/* one item */
li:nth-child(1):nth-last-child(1) {
    width: 100%;
}

/* two items */
li:nth-child(1):nth-last-child(2),
li:nth-child(2):nth-last-child(1) {
    width: 50%;
}

/* three items */
li:nth-child(1):nth-last-child(3),
li:nth-child(2):nth-last-child(2),
li:nth-child(3):nth-last-child(1) {
    width: 33.3333%;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM