CSS實現三欄佈局的方法(自適應)

經典CSS題目:三欄佈局

假設頁面高度已知,請寫出三欄佈局,其中左欄、右欄寬度各爲300px,中間自適應。(以下圖所示)

截屏2019-10-12上午7.39.17.png

  • 方法1:浮動解決方案
<style>

.layout{

width: 100%;

min-height: 200px;

}

.layout .left{

float:

left;width: 300px;

background: red;

}

.layout .right{

float: right;

width: 300px;background: blue;

}

.layout .center{

background: yellow;

}

</style>

<section class="layout float">

<div class="left">左</div>

<div class="right">右</div>

<div class="center">中</div>

</section>
  • 方法2:定位
<style>

.layout{

width: 100%;

min-height: 200px;

}

.layout .left{

position: absolute;

left: 0;

width: 300px;

background: red;

}

.layout .right{

position: absolute;

right: 0;

width: 300px;

background: blue;

}

.layout .center{

left: 300px;

right: 300px;

background: yellow;

}

</style>

<section class="layout absolute">

<div class="left">左</div>

<div class="right">右</div>

<div class="center">中</div>

</section>
  • 方法3:flexbox
<style>

.layout{

width: 100%;

display: flex;

min-height: 200px;

}

.layout .left{

width: 300px;

background: red;

}

.layout .right{

width: 300px;

background: blue;

}

.layout .center{

flex: 1;

background: yellow;

}

</style>

<section class="layout flexbox">

<div class="left">左</div>

<div class="center">中</div>

<div class="right">右</div>

</section>
  • 方法4:表格
<style>

.layout{

width: 100%;

display: table;

min-height: 200px;

}

.layout>div{

display: table-cell;

}

.layout .left{

width: 300px;

background: red;

}

.layout .right{

width: 300px;

background: blue;

}

.layout .center{

flex: 1;

background: yellow;

}

</style>

<section class="layout table">

<div class="left">左</div>

<div class="center">中</div>

<div class="right">右</div>

</section>
  • 方法5:網格佈局
<style>

.layout{

width: 100%;

display: grid;

grid-template-columns: 300px auto 300px;

grid-template-rows: 100px;

}

.layout .left{

background: red;

}

.layout .right{

background: blue;

}

.layout .center{

background: yellow;

}

</style>

<section class="layout grid">

<div class="left">左</div>

<div class="center">中</div>

<div class="right">右</div>

</section>
相關文章
相關標籤/搜索