转自: http://zhoukekestar.github.io/notes/2017/06/07/interview-answers.html
要求:不少于三种方法
所有方案:父元素的宽度为单位为%
absolute + padding
<style>
.example-1 {
position: relative;
height: 100px;
width: 60%;
padding-left: 100px;
}
.example-1 .left {
position: absolute;
width: 100px;
left: 0;
height: 100%;
background: #0f0;
}
.example-1 .right {
background: #f00;
width: 100%;
height: 100%;
}
</style>
<div class='example-1 auto-width'>
<div class='left'>left</div>
<div class='right'>right</div>
</div>
小结:父元素设置padding-left是给左边元素预留空间,左边元素绝对定位到该位置。
flex,未来趋势,推荐!
<style>
.example-2 {
display: flex;
height: 100px;
width: 60%;
}
.example-2 .left {
flex:0 0 100px;
height: 100%;
background: #0f0;
}
.example-2 .right {
flex: 1;
background: #f00;
height: 100%;
}
</style>
<div class='example-2 auto-width'>
<div class='left'>left</div>
<div class='right'>right</div>
</div>
小结:flow属性为flow-grow,flow-shrink,flow-basis属性缩写。
table
<style>
.example-3 {
display: table;
height: 100px;
width: 60%;
}
.example-3 .left {
width: 100px;
height: 100%;
background: #0f0;
display: table-cell;
}
.example-3 .right {
background: #f00;
height: 100%;
display: table-cell;
}
</style>
<div class='example-3 auto-width'>
<div class='left'>left</div>
<div class='right'>right</div>
</div>
小结:如果表格元素未设置宽度,则宽度为表格除了其他元素外,剩余空间。
float 解决方案
<style>
.example-4 {
height: 100px;
width: 60%;
}
.example-4 .left {
float: left;
width: 100px;
height: 100%;
background: #0f0;
}
.example-4 .right {
background: #f00;
overflow: hidden;
height: 100%;
}
</style>
<div class='example-4 auto-width'>
<div class='left'>left</div>
<div class='right'>right</div>
</div>
小结:(1)元素如果不设置宽度,则默认继承父元素宽度 (2)overflow:hidden; 清除左边元素浮动 (3)右边元素未设置宽度,则宽度=父元素宽度-左边元素宽度;
BFC原理:因为BFC内部的元素和外部的元素绝对不会互相影响,因此, 当BFC外部存在浮动时,它不应该影响BFC内部Box的布局,BFC会通过变窄,而不与浮动有重叠。
使用 float+calc属性
<style>
.example-5 {
height: 100px;
width: 60%;
}
.example-5:after {
clear: both;
}
.example-5 .left {
width: 100px;
height: 100%;
background: #0f0;
float: left;
}
.example-5 .right {
background: #f00;
height: 100%;
width: calc(100% - 100px);
float: right;
}
</style>
<div class='example-5 auto-width'>
<div class='left'>left</div>
<div class='right'>right</div>
</div>