实现左边div固定宽度,右边div自适应撑满剩下的宽度的布局方式:
html:
<div class="container">
<div class="left">
left固定宽度200px
</div>
<div class="right">
可变宽度rightrightrightrightrightrightrightrightri
</div>
</div>
方式一:利用bfc
.left{
width:200px;
float:left;
background:red;
}
.right{
overflow:hidden;
background:blue;
}
右边盒子触发bfc,使其不与浮动盒子区域重叠,因此会重新计算宽度。
左边的浮动元素可以不设置具体宽度,配合margin-right和overflow:hidden。右边依旧可以自适应
于是,我们可能就会有:
.float-left { float: left; margin-right: 20px; } .bfc-content { overflow: hidden; background-color: #beceeb; }
的自适应固定搭配。再配合CSS样式库的margin
和padding
家族,快速布局可谓所向披靡。
方式二:左浮动+margin-left
.left{
width:200px;
float:left;
border: 2px solid blue;
background:red;
}
.right{
border: 2px solid yellow;
margin-left:200px;
background:blue;
}
方式三:flex布局
.container{
display:flex;/*设为伸缩容器*/
}
.left{
width:200px;
border: 2px solid blue;
background:red;
}
.right{
border: 2px solid yellow;
flex:1;/*这里设置为占比1,填充满剩余空间*/
background:blue;
}
方式四:浮动+display:table-cell
display:table-cell 让元素表现得像单元格一样,IE8+以上浏览器才支持。跟display:inline-block
一样,会跟随内部元素的宽度显示,看样子也是不合适的命。但是,单元格有个非常神奇的特性,就是你宽度值设置地再大,大到西伯利亚,实际宽度也不会超过表格容器的宽度。
因此,如果我们把display:table-cell
这个BFC元素宽度设置很大,比方说3000像素。那其实就跟block
水平元素自动适应容器空间效果一模一样了。除非你的容器宽度超过3000像素,实际上,一般web页面不会有3000像素宽的模块的。所以,要是你实在不放心,设个9999
像素值好了!
.float-left { float: left; } .bfc-content { display: table-cell; width: 9999px; }
看上去,好像还不错。但是,还是有两点制约,一是IE8+以上浏览器兼容,有些苦逼的团队还要管IE6;二是应付连续英文字符换行有些吃力(可以用word-break:break-all解决)。但是,总体来看,适用的场景要比overflow:hidden
广博很多。
两边定宽,中间自适应布局的四种实现方法
1. 浮动法
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>两边定宽,中间自适应</title> <style type="text/css"> html,body,div{
</
2. 定位法
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>两边定宽,中间自适应</title> <style type="text/css"> html,body,div{
height: 80%;
border:3px solid black;
} .parent{ position: relative; } .left{ width: 300px; position: absolute; left: 0; } .right{ width: 300px; position: absolute; right: 0; } .center{ margin: auto 300px; } </style> </head> <body> <div class="parent"> <div class="left"></div> <div class="right"></div> <div class="center"></div> </div> </body> </html>
3. 弹性盒子法
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>两边定宽,中间自适应</title> <style type="text/css"> html,body,div{
height: 80%;
border:3px solid black;
} .parent{ display: flex; } .left{ width: 300px; } .right{ width: 300px; } .center{ flex:1; } </style> </head> <body> <div class="parent"> <div class="left"></div> <div class="center"></div> <div class="right"></div> </div> </body> </html>
4.calc计算法
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>两边定宽,中间自适应</title> <style type="text/css"> html,body,div{ height: 80%;
border:3px solid black; } .left{ width: 300px; float: left; background-color: red; } .right{ width: 300px; float: right; background-color: yellow; } .center{ width: calc(100% - 620px); margin: 0 auto; background-color: green; } </style> </head> <body> <div class="left"></div> <div class="right"></div> <div class=