左侧固定,右侧自适应如何来写
由于在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;
}
.container{
position: relative;
}
.left{
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 200px;
background: green;
}
.right{
margin-left: 200px;
height: 200px;
background: red;
}
.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;
}