固定宽度div在右边,填充左边的剩余宽度div

时间:2011-11-11 13:42:16

标签: html css

我正在寻找一种方法,将2个div作为列,其中右边的div有一个固定的宽度,div在左边填充剩余的空间。

有没有人碰巧知道是否可以这样做?

我的尝试(在block1下面呈现block2)

<style>
.block1 {
   width: auto;
   height: 200px;

   background-color: green;
}
.block2 {
   float: right;
   height: 200px;
   width: 200px;

   background-color: red;
}
</style>

<div class="block1">test1</div>
<div class="block2">test2</div>

4 个答案:

答案 0 :(得分:24)

你可以这样做:

<强> HTML:

<div class="right">right</div>
<div class="left">left</div>

<强> CSS:

.left{
    background:red;

}
.right{
    float:right;
    width:200px;
    background:green
}

查看此实例http://jsfiddle.net/QHTeS/2/

答案 1 :(得分:6)

浮动剩下的两个元素:

<style>
.block1 {
   width: auto;
   height: 200px;
   float: left;
   background-color: green;
}
.block2 {
   float: left;
   height: 200px;
   width: 200px;

   background-color: red;
}
</style>

<div class="block1">test1</div>
<div class="block2">test2</div>

您应该将它们包装在容器中,以防止弄乱其余的布局。 :)

http://jsfiddle.net/tcFjN/


那是错误的!

在父级上使用display: table;,在子级上使用display: table-cell;

<div id="wrapper">
    <div class="block1">test1</div>
    <div class="block2">test2</div>
</div>


#wrapper
{
    display: table;
    width: 100%;
}

.block1 {
       width: auto;
       height: 200px;
       display: table-cell;
       background-color: green;
}
.block2 {
       display: table-cell;
       height: 200px;
       width: 200px;
       background-color: red;
    }

http://jsfiddle.net/tcFjN/1/

答案 2 :(得分:1)

Check this jsfiddle

从包含左右<div>的容器#container<div>)开始。向右浮动一个<div>并给它一个特定的宽度(在我的例子中为320px)。然后给另一个<div>一个绝对位置,从绝对左边(0px)开始,到右边<div>左边缘(320px)。

如果您调整#container的宽度,则右<div>将保持固定为320px,而左<div>将展开以填充剩余区域。

答案 3 :(得分:1)

这是我没有花车的解决方案。唯一需要注意的是我需要使用包装器。所以,如果所需的HTML是

parent (has a border, margin, padding,...)
  left (fixed width)
  right (variable width, fill the entire space)

我必须将其重写为

   parent (has a border, margin, padding,...)
      wrapper (has no styling)
        left (fixed width)
        right (variable eidthm, fill the entire space)

我的HTML

  <div style="border:1px solid black; background:red; margin:10px; padding:10px;" >
    <div style=""> 
      <div style="display:table-cell; padding:10px; min-width:100px; max-width:100px;background:green;">Left</div>
      <div style="display:table-cell; padding:10px; width:100%; background:yellow;">Main content</div>
    </div>
  </div>

这里的要点是:

  • 不使用显示:表格,因为我们无法设置边框
  • 使用min-width,max-width
  • 使用宽度:100%
相关问题