div宽度怎么自适应

一排有2个div,其中右边的宽度固定,怎么让左边的div自动填满剩余的宽度?不用js实现

阅读 7.9k
9 个回答

如果考虑dom顺序的话可以

<div class="left">
    <div class="content">
        left
    </div>
</div>
<div class="right">right</div>
html,body{height: 100%;overflow: hidden;}
.left{float: left;width:100%;background: #f00;height: 100%;}
.content{margin-right: 200px;}
.right{float: left;width:200px; height: 100%;  margin-left: -200px; background: #ccc;}

不考虑边框那些的话,用 CSS3 的做法是:

.div1 {
  width: 100px;
}
.div2 {
  width: calc(100% - 100px);
}

感觉有歧义啊,两个都固定了一共三个div,那么第三个宽度不是也固定了吗

新手上路,请多包涵

可以用浮动或者绝对定位,flexbox应该也可以的。

  1. flex

  2. rightBox { float:right } .leftBox { position:absolute; left:0; right: .rightBox.width() }

  3. rightBox { float:right; } .leftBox { padding-right: .rightBox.width() }

<style type="text/css">
    #container {
        width: 900px;
        height: 400px;
        background: #f5f5f5;

        position: relative;
        padding-right: 300px;
    }

    #right {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        width: 300px;

        background: #e5e5e5;
    }
</style>


<div id="container">
    <div id="left">这是左侧宽度自适应内容区域</div>
    <div id="right">这是右侧固定宽度300px的区域</div>
</div>

以上DEMO中需要注意的有如下几点:

  1. container 的定位需要为 relative (或者absolute、fixed也可以),其次,padding-right 设置的宽度为右边DIV的宽度;

  2. 通过absolute绝对定位为 #right 右侧DIV进行定位显示

#sidebar{
background:red;
float:right;
width:300px;
}
#content{
background:green;
margin-right:300px;
}
.th{
height:100px;
background:gray;
}
#footer{
background:gray;
height:100px;
}
<div id="wrap">
<div id="sidebar" style="height:240px;">固定宽度区</div>
<div id="content" style="height:340px;">自适应区</div>
  </div>
  <div id="footer">后面的一个DIV,以确保前面的定位不会导致后面的变形</div>

给右边的div固定宽度,左边的box-flex值为1

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题