理解CSS中的浮动更好

时间:2014-01-19 00:51:21

标签: css

我有以下3个div(左中和右)。它的行为完全符合我的预期:

         #leftPane,#rightPane,{
         width: 250px;
         height: 200px;
      border: 1px solid blue;

           }
        #centerPane {
      height: 200px;

               }
            #leftPane {
                  float: left;
                }
               #rightPane {
                 float: right;
              }

这是我的HTML:

          <div id="leftPane">Left Pane</div>
            <div id="rightPane">Right Pane</div>
          <div id="centerPane">Center Pane</div>

我想让中心div具有可调节的宽度,因为我将需要左右窗格可折叠。请注意,文本“中心窗格”距左侧250px。这是我想要的,但现在我想添加填充,背景颜色等,但我将其添加到我的HTML:

      <div id="centerPane"><div style="background:#cccccc;">Center Pane</div></div>

我认为灰色背景颜色只会在“中心文字”周围,但它会一直穿过屏幕的宽度。所以我很困惑为什么centerPane的文本行为正确,但添加到中心div的任何样式都跨越了屏幕的宽度。谁能告诉我如何在左右窗格div之间设置centerPane内容的样式?谢谢

2 个答案:

答案 0 :(得分:2)

听起来你想在中心div上使用float: left。发生的事情是左边和右边的div不在文档流程中(它们不会影响其他任何东西),所以中心div占据了相同的区域。如果您在中心使用clear:both,它将位于左下方,因为这会修复文档流程。由于您希望中心位于中心,因此您还需要将其向左浮动,以便它位于左侧div旁边。

overflow: hidden将在这种情况下修复背景,但布局很难 - 特别是当窗口较小时(看看中心div会发生什么)。我会在下面的回答中使用display:table-cell

<强> Live demo (click).

您可能还对display: inline-blockdisplay: table-cell

感兴趣

显示表格单元格

<div class="container">
  <div id="leftPane">Left Pane</div>
  <div id="centerPane">Center Pane</div>
  <div id="rightPane">Right Pane</div>
</div>

<强> CSS:

.container {
  display: table;
  width: 100%;
}

.container div {
  display: table-cell;
  border: 1px solid blue;
  width: 250px;
}
#centerPane { 
  background: #ccc;
  width: auto;
}

<强> Live demo (click).

答案 1 :(得分:1)

溢出:隐藏;将包含背景。

<div id="centerPane"><div style="background:#cccccc;overflow:hidden">Center Pane</div></div>
相关问题