CSS:如何使三个div横向浮动,并宽度为100%而不混乱?

3
我希望在页面中放置三个div { width:33%; border: 3px solid #333;},但是总宽度似乎超过了100%,导致失败。
如何让三个div并排浮动,并占据100%的宽度而不出现问题?
3个回答

7
边框不计入div的盒子大小。它们是要添加的,因此会干扰你的设定,其宽度为:3个盒子 * (33%+3px+3px),这很可能超过100%。
使用:
.left {
  float:left; 
  width:33.3%;
  border: 3px solid #333;
}
.box-sizing { box-sizing: border-box; }

请查看Fiddle演示,您可以调整结果框的大小,它仍然完美。 :)


3
请注意,box-sizing属性不被 IE lt 8支持。 ;) - Saucier
还有什么好说的?IE6和IE7已经是过时的浏览器了。 - cimmanon
我专注于未来而非过去。 - Hugolpz

1
我刚偶然看到这个问题。虽然我认为Hugolpz的答案很好,但我忍不住在jsfiddle上玩耍。因此,我的答案是一种实验性的解决方案,没有在真实世界场景中测试过。但我觉得它有点有趣。这里是fiddle
标记:
<div class="outer">
    <div class="box one">1</div>
    <div class="box two">2</div>
    <div class="box three">3</div>
</div>

样式:

// Color and height properties are just here for demonstration purposes.

.outer {
    position: relative; // make the parent a relative reference point to its children
    // overflow: hidden;
    height: 40px;
    background: yellow;
}
.box {
    position: absolute; // position all children absolute but relative to the parent
    width: 33.3%;
    border: 5px solid blue;
}
.one {
    left: 0; // first box to the left
    background: red;
}
.two {
    left: 33.3%; // second box placed according to the width of the first box
    background: cyan;
}
.three {
    left: 66.6%; // third box placed according to the sum of widths of the first two boxes
    background: purple;
}

邻近框的左右边框会由于它们的绝对定位而重叠。在这种情况下,人们期望边框变为10px,但实际上它们看起来只有5px。

在大多数实际情况下,使用绝对定位进行布局会失败,因为它需要知道内容的高度。 - cimmanon
@cimmanon 是的,就像我说的,未经测试等等。我只是被激发了起来,想玩一下,然后分享我的代码片段。:) 我们应该投票删除这个回答吗? - Saucier
+1 这是一个有帮助的解决方案。绝对不要删除它,也不应该被投票否定。我知道我的内容高度,所以这是一个有效的解决方案,特别是因为其他答案中的“box-sizing”解决方案在IE8及以下版本中无法工作。谢谢! - Doug S

1
你的代码问题在于你设置了每个div的大小为33% + 6px边框。

要解决这个问题,你可以简单地使用box-sizing,并确保重置所有样式。

示例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <style type='text/css'>
            * { margin:0; padding:0; border:0; outline:0; } 
            .thirdContainer { float: left; display: block;  width: 33.33%; box-sizing: border-box; height: 100px;}
    </style>
</head>
<body>
    <div class="thirdContainer" style="background: yellow;"></div>
    <div class="thirdContainer" style="background: yellowgreen;"></div>
    <div class="thirdContainer" style="background: blue;"></div>

</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接