自动调整子div,以便它们均等地分享父的宽度 [英] Auto resize child divs so they equally share width of parent

查看:120
本文介绍了自动调整子div,以便它们均等地分享父的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个固定宽度为320px的父div,并且我希望能够(或者我希望我的用户能够)向父级添加任何数量的子div,并让它们自动调整为共享父级的宽度。



我不想让父宽度改变,我也不想用任何类型的滚动溢出来做 - 我只需要divs里面适合



如果只有一个孩子,那么宽度是100%,如果有两个,那么他们的宽度是50%每个等



这个?



我已经通过css接触了很多不同的方法,但似乎不能明白。我假设这必须用某种JavaScript,但我不知道足够拉它。



但是,如果只用css就可以做到。





(不知道你是否需要知道这一点,但是孩子的div将没有文本,它们只是空白的背景颜色和固定高度)



示例代码:



CSS

  .box {
margin:10px;
background:white;
border-radius:6px;
border:1px solid darken(white,12%);
-webkit-box-shadow:0px 1px 4px rgba(50,50,50,0.07);
-moz-box-shadow:0px 1px 4px rgba(50,50,50,0.07);
box-shadow:0px 1px 4px rgba(50,50,50,0.07);
float:left;
}

.line {
height:6px;
opacity:0.4;
-moz-opacity:0.4;
filter:alpha(opacity = 4);
margin-bottom:-1px;
float:left;
}

HTML

  ... 

< div class =box>
< div class =line>& nbsp;< / div>
< / div>

...

#将能够添加任何数量的.lines


解决方案

使用 display:table (和 table-layout:fixed 用于容器的固定宽度(如果需要等宽列)和 display:table-cell $ b

Let's say I have a parent div with a fixed width of 320px and I want to be able to (or I want my users to be able to) add any amount of child divs to the parent and have them all adjust automatically to share the width of the parent.

I don't want the parent width to change, nor do I want to do this with any sort of scrolling overflow - I just need for the divs inside to fit the width of the parent equally.

For example,

If there is only one child then the width is 100%, if there are two then their width is 50% each etc

How would I go about doing this?

I've approached this many different ways with css, but can't seem to figure it out. I'm assuming this has to be done with some sort of javascript, but I don't know enough to pull it off.

But, If it can be done with just css, that would be great.

Thanks in advance.

(Don't know if you'll need to know this, but the child divs will have no text. They're just blank with background-color and fixed height)

Example code:

CSS

.box {
margin: 10px;
background: white;
border-radius: 6px;
border: 1px solid darken(white, 12%);
-webkit-box-shadow: 0px 1px 4px rgba(50, 50, 50, 0.07);
-moz-box-shadow:    0px 1px 4px rgba(50, 50, 50, 0.07);
box-shadow:         0px 1px 4px rgba(50, 50, 50, 0.07);
float: left;
}

.line {
height: 6px;
opacity: 0.4;
-moz-opacity: 0.4;
filter:alpha(opacity=4);
margin-bottom: -1px;
float: left;
}

HTML

...

<div class="box">
<div class="line">&nbsp;</div>
</div>

...

#will be able to add any amount of .lines

解决方案

Use display: table (and table-layout: fixed with fixed width for container if you need equal-width columns) for container and display: table-cell for child elements.

这篇关于自动调整子div,以便它们均等地分享父的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆