在前端的面試中,常常會遇到的一個問題就是「怎麼實現左右兩端寬度固定,中間自適應」。下面我總結了五種常見的方式實現。html
先寫下全局的 style 吧前端
<style>
html * {
padding: 0;
margin: 0;
}
.layout {
margin-top: 10px;
}
.layout article div
{
min-height: 100px;
}
</style>複製代碼
缺點:當 center 塊的內容太長,就會使得 center 部分溢出;解決方式就是建立 BFC面試
<section class="layout float">
<style>
.layout.float .left {
width: 300px;
float: left;
background: yellow;
}
.layout.float .right {
width: 300px;
float: right;
background: blue;
}
.layout.float .center {
background: red;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<h2>個人float佈局解決方案</h2>
</div>
</article>
</section>複製代碼
缺點:絕對定位脫離文檔流瀏覽器
<section class="layout absoluted">
<style>
.layout.absoluted .left-center-right>div {
position: absolute;
}
.layout.absoluted .left {
left: 0px;
width: 300px;
background: yellow;
}
.layout.absoluted .center {
left: 300px;
right: 300px;
background: red;
}
.layout.absoluted .right {
right: 0px;
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h2>我是absoluted佈局解決方案</h2>
</div>
<div class="right"></div>
</article>
</section>複製代碼
<section class="layout flexb">
<style>
.layout.flexb {
margin-top: 120px;
}
.layout.flexb .left-center-right {
display: flex;
}
.layout.flexb .left {
width: 300px;
background: yellow;
}
.layout.flexb .center {
flex: 1;
background: red;
}
.layout.flexb .right {
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h2>我是flex解決方案</h2>
</div>
<div class="right"></div>
</article>
</section>複製代碼
缺點:table 佈局影響性能,一小局部的變化,都會致使 DOM 從新渲染bash
<section class="layout table">
<style>
.layout.table .left-center-right {
display: table;
width: 100%;
height: 100px;
}
.layout.table .left-center-right>div {
display: table-cell;
}
.layout.table .left {
width: 300px;
background: yellow;
}
.layout.table .center {
background: red;
}
.layout.table .right {
width: 300px;
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h2>我是Table解決方案</h2>
</div>
<div class="right"></div>
</article>
</section>複製代碼
缺點:瀏覽器的兼容性欠佳佈局
<section class="layout grid">
<style>
.layout.grid .left-center-right {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.layout.grid .left {
background: yellow;
}
.layout.grid .center {
background: red;
}
.layout.grid .right {
background: blue;
}
</style>
<article class="left-center-right">
<div class="left"></div>
<div class="center">
<h2>我是grid解決方案</h2>
</div>
<div class="right"></div>
</article> </section>複製代碼
效果圖以下:性能
若是對你有幫助的話,點個贊讓我知道唄~flex