html - 向 float 元素添加边框会导致最后一个 div 换行

标签 html css

我有以下 html/css。当我关闭边框时,一切都正确排列,但如果我将边框放在中心 div 上,则右侧的内容会显示在其他所有内容下方。我该如何解决这个问题?

#container {} #left {
  width: 20%;
  float: left;
}
#center {
  width: 60%;
  float: left;
  border-left: 1px solid black; /*this causes the 'right' div to wrap*/
  border-right: 1px solid black; /*this causes the 'right' div to wrap*/
}
#right {
  float: left;
  width: 20%;
}
<div id="container">
  <div id="left">I am left</div>
  <div id="center">I am center</div>
  <div id="right">I am right</div>
  <div style="clear: both;"></div>
</div>

最佳答案

您需要添加 box-sizing: border-box 以便边框的宽度包含在元素的宽度中,否则它的 60% + 1px + 1px + 2 * 20% 并且大于 100%

#container > * {
  box-sizing: border-box;
}
#left {
  width: 20%;
  float: left;
}
#center {
  width: 60%;
  float: left;
  border-left: 1px solid black;
  border-right: 1px solid black;
}
#right {
  float: left;
  width: 20%;
<div id="container">
  <div id="left">I am left</div>
  <div id="center">I am center</div>
  <div id="right">I am right</div>
  <div style="clear: both;"></div>
</div>

注意:box-sizing: border-box 还将包括 padding 但不包括边距。

关于html - 向 float 元素添加边框会导致最后一个 div 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105474/

相关文章:

html - Flexbox 以相同的方式定位所有内容。有什么办法让它表现不同吗?

javascript - 图像/容器下的空白...由于类别或图像尺寸?

html - 为什么我的 DIV 没有显示在移动设备上?

css - 连接输入字段和按钮引导模式

html - 在 div 中彼此相邻

jquery - Bootstrap popover 裁剪到包含 div 的范围

javascript - 使用 HTML5/Canvas/JavaScript 等复制 BBC iPlayer 旋转效果

html - 使用 bootstrap 4 围绕一个圆对齐不同的图像并在轨道上旋转并在悬停时以圆圈显示文本

html - 自定义 HTML 元素扩展另一个自定义元素

HTML在IE6中 float 清除问题