本文介紹了詳解左右寬度固定中間自適應(yīng)html布局解決方案,分享給大家,具體如下:
a.使用浮動布局
html結(jié)構(gòu)如下
<div class="box">
<div class="left">left</div>
<div class="right">right</div>
<div class="center">center</div>
</div>
//此處注意要先渲染左、右浮動的元素才到中間的元素。元素浮動后剩余兄弟塊級元素會占滿父元素的寬度
<style>
.box{
height:200px;
}
.left{
float:left;
width:300px;
}
.right{
float:right;
width:300px;
}
</style>
b.使用固定定位
html結(jié)構(gòu)如下
<div class="box">
<div class="left">left</div>
<div class="right">right</div>
<div class="center">center</div>
</div>
//和浮動布局同理,先渲染左右元素,使其定位在父元素的左右兩端,剩余的中間元素占滿父元素剩余寬度。
<style>
.box{
position: relative;
}
.left{
position: absolute;
width: 100px;
left: 0;
}
.right{
width:100px;
position: absolute;
right: 0;
}
.center{
margin: 0 100px;
background: red;
}
</style>
c.表格布局
將父元素display:table,子元素display:table-cell,會將它變?yōu)樾袃?nèi)塊。
這種布局方式的優(yōu)點是兼容性好。
<div class="box">
<div class="left">
left
</div>
<div class="center">
center
</div>
<div class="right">
right
</div>
</div>
<style>
.box{
display: table;
width: 100%;
}
.left{
display: table-cell;
width: 100px;
left: 0;
}
.right{
width:100px;
display: table-cell;
}
.center{
width: 100%;
background: red;
}
</style>
d.彈性布局
父元素display:flex子元素會全部并列在一排。
子元素中flex:n的寬度會將父元素的寬度/n
如flex:1,寬度就等于父元素高度。
彈性布局的缺點是兼容性不高,目前IE瀏覽器無法使用彈性布局
<div class="box">
<div class="left">
left
</div>
<div class="center">
center
</div>
<div class="right">
right
</div>
</div>
<style>
.box{
display: flex;
width: 100%;
}
.left{
width: 100px;
left: 0;
}
.right{
width:100px;
}
.center{
flex:1;
}
</style>
e.網(wǎng)格布局
父元素display:grid;
grid-templatecolumns:100px auto 100px;
依次為第一個子元素寬100px 第二個自適應(yīng) 第三個100px;
網(wǎng)格布局的優(yōu)點是極為簡便,直接通過父元素樣式?jīng)Q定,缺點是兼容性不高。
<div class="box">
<div class="left">
left
</div>
<div class="center">
center
</div>
<div class="right">
right
</div>
</div>
<style>
.box{
display: grid;
grid-template-columns: 100px auto 100px;
width: 100%;
}
</style>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。