小编典典

等距DIV的流体宽度

html

我有一个宽度可变的容器DIV。

在此我有4个DIV,所有300px x 250px …

<div id="container">
   <div class="box1"> </div>
   <div class="box2"> </div>
   <div class="box3"> </div>
   <div class="box4"> </div>
</div>

我想发生的是框1向左浮动,框4向右浮动,框2和3在它们之间均匀分布。我希望间隔也要流畅,以便将浏览器做得更小,空间也要变小。


阅读 463

收藏
2020-05-14

共1个答案

小编典典

  • 可以在IE6 +和所有现代浏览器中使用!
  • 我将您要求的尺寸减半,以使其易于使用。
  • text-align: justify结合在一起.stretch是在处理定位。
  • display:inline-block; *display:inline; zoom:1修复inline-block了IE6 / 7
  • font-size: 0; line-height: 0修复了IE6中的一个小问题。
#container {
  border: 2px dashed #444;
  height: 125px;
  text-align: justify;
  -ms-text-justify: distribute-all-lines;
  text-justify: distribute-all-lines;
  /* just for demo */
  min-width: 612px;
}

.box1,
.box2,
.box3,
.box4 {
  width: 150px;
  height: 125px;
  vertical-align: top;
  display: inline-block;
  *display: inline;
  zoom: 1
}

.stretch {
  width: 100%;
  display: inline-block;
  font-size: 0;
  line-height: 0
}

.box1,
.box3 {
  background: #ccc
}

.box2,
.box4 {
  background: #0ff
}
<div id="container">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
  <span class="stretch"></span>
</div>

多余的span(.stretch)可以替换为:after。

这仍然工作在所有的浏览器相同的上述溶液。:after不适用于IE6 / 7,但distribute-all-lines无论如何他们都在使用,所以没关系。

有一个小缺点:after:要使最后一行在Safari中完美工作,您必须注意HTML中的空白。

具体来说,这不起作用:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div>
</div>

这样做:

<div id="container">
    ..
    <div class="box3"></div>
    <div class="box4"></div></div>

您可以将其用于任意数量的child,div而无需boxN通过更改将类添加到每个子类中

.box1, .box2, .box3, .box4 { ...

#container > div { ...

这将选择作为div的第一个子元素的任何div #container,并且其下没有其他任何div 。要概括背景色,可以使用CSS3 n阶选择器,尽管仅IE9 +和其他现代浏览器支持它:

.box1, .box3 { ...

变成:

#container > div:nth-child(odd) { ...
2020-05-14