在前端的面試中,經常會遇到的一個問題就是“怎麼實現左右兩端寬度固定,中間自適應”。下面我總結了五種常見的方式實現。
先寫下全域性的 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>複製程式碼
方法二:通過 absoluted 佈局
缺點:絕對定位脫離文件流
<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>複製程式碼
方法三:使用 CSS3 的 flex 佈局
<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 佈局
缺點:table 佈局影響效能,一小區域性的變化,都會導致 DOM 重新渲染
<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>複製程式碼
方法五:使用 CSS3 的 grid 佈局
缺點:瀏覽器的相容性欠佳
<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>複製程式碼
效果圖如下:
如果對你有幫助的話,點個贊讓我知道唄~