CSS并排div的自动等宽
<div id="wrapper" style="width:90%;height:100px;background-color:Gray;">
<div id="one" style="height:100px;background-color:Green;float:left;"></div>
<div id="two" style="height:100px;background-color:blue;float:left;"></div>
<div id="three" style="height:100px;background-color:Red;float:left;"></div>
</div>
我有一个父div,其中将包含2或3个子div。 我希望子div自动采用相等的宽度。
谢谢
Faizal Balsania asked 2020-02-22T16:07:26Z
5个解决方案
96 votes
这不是不可能的。 使用div
,甚至还不是特别困难。
该解决方案将在现代浏览器中运行。 在IE7中将无法使用。
[http://jsfiddle.net/g4dGz/](三个div
s)
[http://jsfiddle.net/g4dGz/1/](两个div
s)
CSS:
#wrapper {
display: table;
table-layout: fixed;
width:90%;
height:100px;
background-color:Gray;
}
#wrapper div {
display: table-cell;
height:100px;
}
HTML:
<div id="wrapper">
<div id="one">one one one one one one one one one one one one one one one one one one one one one</div>
<div id="two">two two two two two two</div>
<div id="three">three</div>
</div>
34 votes
在现代浏览器中,您可以使用flexbox
三个divs示例
两个divs示例
CSS:
#wrapper {
display: flex;
width:90%;
height:100px;
background-color:Gray;
}
#wrapper div {
flex-basis: 100%;
}
HTML:
<div id="wrapper">
<div id="one">one one one one one one one one one one one one one one one one one one one one one</div>
<div id="two">two two two two two two</div>
2 votes
您是否尝试使用width:33%
?
2 votes
为了与旧版浏览器兼容,下面提供了一种可行的解决方案。
的HTML:
<div class="parent">
<div></div>
<div></div>
<div></div>
</div>
CSS:
.parent{
height: 200px;
background: #f00;
}
.parent > div{
width: calc(100%/3);
height: 100%;
float: left;
background: #fff;
}
但是,为了使它动态,因为您知道它是2列还是3列,所以可以将count放在变量中并执行内部/内联css:
// $ count = 2或3
内部CSS(推荐)
...
<style>
.parent > div{
width: calc(100%/<?=$count;?>);
}
</style>
<body>
...
内联CSS:
<div class="parent">
<div style="calc(100%/<?=$count;?>)"></div>
<div style="calc(100%/<?=$count;?>)"></div>
<div style="calc(100%/<?=$count;?>)"></div>
</div>
0 votes
.wrapper > div {
width: 33.3%;
}
这在IE <= 6中不起作用,因此您最好向子div添加一些通用类并为其创建CSS规则。