左固定,右自適應(yīng)
首先是html代碼:
<div class="parent">
<div class="left">固定</div>
<div class="right">自適應(yīng)</div>
</div>
方法:直接只用float就可以,不知道以下方法加上的好處?
方法一:使用float+margin-left實現(xiàn)
.left{
background-color: pink;
height: 300px;
width: 200px;
float: left;
}
.right{
background-color: green;
height: 300px;
margin-left:200px;
}
左側(cè)布局左浮動,定寬,右側(cè)布局margin-left:左側(cè)寬度;
方法二:使用float+overflow:auto/hidden
.left{
background-color: pink;
height: 300px;
width: 200px;
float: left;
}
.right{
background-color: green;
height: 300px;
overflow:auto;
/*overflow:hidden;也可以*/
}
方法三:使用flex
.parent{
display: flex;
}
.left{
background-color: pink;
height: 300px;
flex: 0 0 200px;
}
.right{
background-color: green;
height: 300px;
flex:1 1 auto;
}
使用flex布局,左側(cè)flex:0 0 200px,不擴(kuò)大不縮小,固定寬度,右側(cè)自適應(yīng)擴(kuò)大縮小。
左側(cè)固定200px,右側(cè)自適應(yīng):
image.png
右固定,左自適應(yīng)
還是html代碼:
<div class="parent">
<div class="left">固定區(qū)</div>
<div class="right">自適應(yīng)區(qū)</div>
</div>
方法:使用float:right就行了,不知道加上以下方法的好處?
方法一:使用float+margin-right:
.left{
width:200px;
height: 300px;
background-color: pink;
float: right;
}
.right{
height: 300px;
background-color: green;
margin-right: 200px;
}
html代碼中,固定放在左邊的,但在布局上是在右邊,所以要更改html代碼,此方法就無效了。
image.png
修改html代碼,讓代碼和布局一致:
<div class="parent">
<div class="free">自適應(yīng)區(qū)</div>
<div class="box">固定區(qū)</div>
</div>
方法二:使用absolute+top+right:
.parent{
position: relative;
}
.box{
background-color: green;
width: 200px;
height: 300px;
position: absolute;
right: 0;
top: 0;
}
.free{
margin-right: 200px;
height: 300px;
background-color: pink;
}
就達(dá)到這個效果了,代碼和布局一致:
image.png
但是,使用絕對定位對后面元素的布局不是很好,所以該方法得改進(jìn)。
方法三:使用float+margin:
html代碼:
<div class="parent">
<div class="freeBox">
<div class="free">自適應(yīng)區(qū)</div>
</div>
<div class="box">固定區(qū)</div>
</div>
css代碼:
.freeBox{
float: left;
margin-left: -200px;
width: 100%;
height: 300px;
background-color: green;
}
.free{
margin-left: 200px;
}
.box{
float: right;
width: 200px;
height: 300px;
background-color: pink;
}
圖片顯示:
image.png
方法四:標(biāo)準(zhǔn)方法display:table
沒有那么麻煩的方法:
html代碼:
<div class="parent">
<div class="freeBox">自適應(yīng)區(qū)域</div>
<div class="rightBox">固定區(qū)域</div>
</div>
css代碼:
.parent{
display: table;
width: 100%
}
.freeBox{
display: table-cell;
height: 300px;
background-color: yellow;
}
.rightBox{
display: table-cell;
width: 200px;
background-color: pink;
height: 300px;
}
父元素設(shè)置display為table,寬度100%,子元素都是table-cell,右邊部分設(shè)置寬度,左邊就自適應(yīng)了。
圖片顯示:
image.png
部分參考:http://jo2.org/css-auto-adapt-width/
height和background-color都是為了顯示便于看,不為關(guān)鍵代碼。