【问题标题】:CSS: resize div width according to parents widthCSS:根据父母宽度调整div宽度
【发布时间】:2010-12-14 22:04:41
【问题描述】:

好的,我基本上是在构建一个流畅的布局。 我的 HTML 是这样的:

<div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="center">This text is long and can get longer</div>
    <div class="box" id="right">Right</div>
    <div class="clear"></div>
</div>

这是css:

#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

我需要知道的是,当 #container 重新调整大小而元素不相互移动时,如何让 #center 重新调整大小。

【问题讨论】:

  • 只是一个简单的修正:
    这个文本很长,可以加长
    id是“center” ;)
  • 干杯,我不敢相信我做到了

标签: html css css-float fluid-layout


【解决方案1】:

尝试这些更正(只是简单的浮动元素,无需设置绝对元素或填充)

just added a new fiddle

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>fluid layout</title>
<style>
    /*class to set the width of the columns */
    .floatbox{
        width:100px;
    }

    #container{
        width: 100%;
        float:left;
    }
    #left{
        float:left;
    }
    #right{
        float:right;
    }
    #center{
        overflow: hidden;
    }
    .clear{
        clear:both;
    }
</style>
</head>
<body>
    <div id="container">
        <!-- floating column to the right, it must be placed BEFORE the left one -->
        <div class="floatbox" id="right">Right</div>
        <div class="floatbox" id="left">Left</div>

        <!-- central column, it takes automatically the remaining width, no need to declare further css rules -->
        <div id="center">This text is long and can get longer</div>

        <!-- footer, beneath everything, css is ok -->
        <div class="clear"></div>
    </div>
</body>
</html>

【讨论】:

    【解决方案2】:

    #container 也必须浮动(或溢出:自动/隐藏)才能实现。 我强烈建议您使用一些比较知名的流体解决方案:http://www.noupe.com/css/9-timeless-3-column-layout-techniques.html

    【讨论】:

      【解决方案3】:

      执行此操作并完全避免出现的float 问题的最简单方法是 在容器上使用填充并绝对定位填充区域中的左/右元素。 (http://www.jsfiddle.net/gaby/8gKWq/1 上的演示)

      HTML

      <div id="container">
          <div class="box" id="left">Left</div>
          <div class="box" id="right">Right</div>
          <div class="box" id="centre">This text is long and can get longer</div>
      </div>
      

      div 的顺序不再重要..

      CSS

      #container{
          padding:0 100px;
          position:relative;
      }
      .box{
         /*style the boxes here*/
      }
      #left, #right{
          width: 100px;
          position:absolute;
      }
      #left{left:0;top:0;}
      #right{right:0;top:0;}
      
      #center{
         /*anything specific to the center box should go here.*/
      }
      

      【讨论】:

        猜你喜欢
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多