为每个元素平均划分一个空格

时间:2013-04-29 18:05:58

标签: html css

有没有办法为每个元素平均划分空格(或div)而不指定width的绝对值。只是为了使CSS代码灵活。

例如,如果将这些元素放入div:

<div id="parent">
    <div class="child"></div>
    <div class="child"></div>
</div>

CSS会自动为每个.child元素width=50%

提供

在这个例子中:

<div id="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

CSS还会自动提供每个.child元素width=25%

有可能吗?

3 个答案:

答案 0 :(得分:1)

你必须使用我害怕的表并为子div添加一个包装,你可以这样做:

#parent{
width: 1000px; /* Example width */
height: 100px; /* Example height */
display: table;
table-layout: fixed;
}
.childwrap {
display:table-row;
}
.child{
display: table-cell;
}

示例:http://cssdesk.com/rZKRW

答案 1 :(得分:0)

您可以使用以下jQuery代码:

var childs = $('#parent .child')
    ,width = Math.floor(100/childs.length);
childs.css('width',width+'%');

答案 2 :(得分:-1)

你确定可以。只需将具有所需百分比的值应用于width属性,并确保将已定义的值应用于其父项。一切都好。

.child {
with:50%;
}

或为你的4个孩子......

.child {
 width:25%;
}

为了使其与其他细节一起工作,必须指定祖先宽度。如果祖先的宽度取决于儿童的内容,那么就有可能产生未计算的宽度。

如果你的祖先div本身具有一定的价值,那么就需要它的祖先有一个定义的等等。