这个问题在开发时碰过很是屡次,是经典布局问题。不少公司的面试题也会问这类问题,今天就详细的来谈一下这类问题。css
还有一篇相似的文章,关于三栏布局 详情请戳html
题意很是明确,左侧的块宽度是固定的,右侧的宽度会随着浏览器的宽度变化的,见下图。
css3
为了解决这个问题,首先,咱们来理解一下何为BFC。web
BFC(Block Formatting Context)直译为“块级格式化范围”。面试
BFC提供了一个环境,HTML元素在这个环境中按照必定规则进行布局。它不会影响到其它环境中的布局。能够把它理解成是一个独立的容器,而且这个容器的里box的布局,与这个容器外的绝不相干。浏览器
为了加深咱们理解BFC为什么物,下面看一个例子,上代码。app
.wrapper{ border: 5px solid #000; } .red { background-color:red; } .yellow { background-color:yellow; } .orange { background-color:orange; } .green { background-color:green; } .box{ width:100px; height:100px; float:left; }
<div class="wrapper"> <div class="container"> <div class="red box"></div> <div class="yellow box"></div> </div> <div class="container"> <div class="orange box"></div> <div class="green box"></div> </div> </div>
见效果:
布局
很明显,.wrapper中全部的box都是浮动,父级标签没有被内容撑开,虽然.red、.yellow和.orange和.green是在两个不一样的div中,可是仍不会换行。这是因为设置了浮动元素的块会造成一个BFC布局,前面提到过了:flex
若想要让每个.container中的元素都单独占据一行,可让.container变成BFC布局(overflow:hidden)。
flexbox
看到这里。相信你对BFC也有必定的理解了。如若不理解,能够看看这篇文章,有可取之处。
关于Block Formatting Context--BFC和IE的hasLayout
关于IE的layout能够看看这篇文章
IE的layout属性详解
回到题目,下面来看看如何实现左侧固定,右侧自适应布局
<div class="container"> <div class="left"></div> <div class="right"></div> </div>
因为在BFC中,每个元素左外边与包含块的左边相接触(对于从右到左的格式化,右外边接触右边),即便存在浮动也是如此。建立了BFC的元素不能与浮动元素重叠。且当容器有足够的剩余空间容纳BFC的宽度时,全部浏览器都会将BFC放置在浮动元素所在行的剩余空间内。利用这些特性,就能够达到效果。
.left{ float: left; width: 200px; height: 200px; background: green; } .right{ overflow: hidden; height: 300px; background: red; }
首先仍是设置left浮动让他变为BFC,由2.1方法可知,在BFC中,每个元素左外边与包含块的左边相接触(对于从右到左的格式化,右外边接触右边),即便存在浮动也是如此。因此left和right会重叠。而后利用margin-left让right腾出位置。
.left{ float: left; width: 200px; height: 200px; background: green; } .right{ margin-left: 200px; height: 300px; background: red; }
一样,这个方法和2.2方法相似,也是left的造成BFC方式不一样,就不过多描述了。
.container{ position: relative; } .left{ position: absolute; left: 0; top: 0; width: 200px; height: 200px; background: green; } .right{ margin-left: 200px; height: 200px; background: red; }
flex布局走天下阿。。可是兼容性问题仍是摆在那里,有所取舍吧。
.container{ display: flex; display: -webkit-box; display: -moz-box; display: -ms-flexbox; width:100%; height: 200px; } .left{ width: 200px; background: green; } .right{ // 若是此处用width:100%会致使左侧元素不足固定宽度,由于left+right的宽度大于父级宽度,会进行一个等比缩放 //width:100%; flex:1; background: red; }
.container{ display: grid; grid-template-rows: 200px; grid-template-columns: 200px auto; width:100%; } .left{ background: green; } .right{ background: red; }
.container{ display: table; width:100%; } .left{ display: table-cell; height: 200px; width: 200px; background: green; } .right{ display: table-cell; height: 200px; background: red; }
前面提到了BFC,与之相似的还有IFC,GFC,FFC。。很晕吧,贴上两个连接,但愿你看了能有所收获。
CSS魔法堂:从新认识Box Model、IFC、BFC和Collapsing margins
css3之BFC、IFC、GFC和FFC
以上内容,若有错误请指出,不甚感激。