頁(yè)面布局
這里以一道潮妫考的面試題為例:
假設(shè)高度已知,請(qǐng)寫(xiě)出三欄布局,其中左欄,右欄各位300px,中間自適應(yīng)
這道題有五種寫(xiě)法,分別是float,absolute,flexbox,table(老版本),grid(新技術(shù))
這種面試題看起來(lái)簡(jiǎn)單,但一定要盡可能多的寫(xiě)出答案(至少三種),grid作為css3的新技術(shù),會(huì)讓面試官對(duì)你有一個(gè)好的印象,體現(xiàn)你對(duì)新技術(shù)和新知識(shí)的渴望
下面是代碼:
<body>
<div>
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
</body>
- absolute
* {
margin: 0;
padding: 0;
}
.left {
position: absolute;
left: 0;
width: 300px;
height: 100px;
background-color: red;
}
.right {
position: absolute;
right: 0;
width: 300px;
height: 100px;
background-color: blue;
}
.center {
position: absolute;
left: 300px;
right: 300px;
height: 100px;
background-color: yellow;
}
- table
.table{
display: table;
width: 100%;
height: 100px;
}
.table>div{
display: table-cell;
}
.left{
width: 300px;
background-color: red;
}
.right{
width: 300px;
background-color: blue;
}
.center{
background-color: yellow;
}
- flex
.flex {
display: flex;
}
.flex>div {
height: 100px;
}
.left {
width: 300px;
background-color: red;
}
.right {
width: 300px;
background-color: blue;
}
.center {
flex: 1;
background-color: yellow;
}
- float
* {
padding: 0;
margin: 0;
}
.layout-float .left {
float: left;
width: 300px;
height: 100px;
background-color: red;
}
.layout-float .center {
background-color: yellow;
height: 100px;
}
.layout-float .right {
float: right;
width: 300px;
height: 100px;
background-color: blue;
}
- Grid
.grid {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.left {
background-color: red;
}
.center {
background-color: yellow;
}
.right {
background-color: blue;
}
延伸部分,分析這幾種寫(xiě)法的優(yōu)劣
- 浮動(dòng)的兼容性比較好,但是會(huì)脫離文檔流,處理不好會(huì)導(dǎo)致很多其它問(wèn)題
- absolute快捷鍵便,缺點(diǎn)是會(huì)導(dǎo)致后續(xù)元素全部脫離文檔流
- flex是移動(dòng)端最完美的解決方案,但是ie8以下不支持
- 表格布局在歷史上評(píng)價(jià)不高,缺點(diǎn)很多,現(xiàn)在基本已經(jīng)被廢棄了,優(yōu)點(diǎn)是兼容性好
- Grid布局是新技術(shù),而且寫(xiě)起來(lái)很方便,代碼量也少,缺點(diǎn)就是瀏覽器的兼容問(wèn)題
但是這道題到這里還不算結(jié)束,如果問(wèn)題變成高度未知,這5種方法還有哪些能滿足呢?
這里只有flex和table布局能繼續(xù)滿足要求,繼續(xù)擴(kuò)展下去的問(wèn)題有可能問(wèn)到清除浮動(dòng),BFC等相關(guān)知識(shí)點(diǎn),你是否了解呢?
小結(jié)
- 語(yǔ)義化掌握到位,不要一路div,要使用語(yǔ)義化標(biāo)簽
- 頁(yè)面布局深刻理解,清楚的寫(xiě)出代碼
- CSS基礎(chǔ)扎實(shí):table,grid,flex知識(shí)點(diǎn)
- 思維靈活積極上進(jìn):Grid是最新技術(shù),如果能寫(xiě)出來(lái)則會(huì)突顯你積極上進(jìn),對(duì)新技術(shù)有渴望,知道每個(gè)方案的優(yōu)缺點(diǎn)并加以對(duì)比,找出最符合業(yè)務(wù)場(chǎng)景的解決辦法,才能體現(xiàn)出你思維靈活
- 代碼書(shū)寫(xiě)規(guī)范,縮進(jìn),類名等等
三欄布局的變通
- 左右固定,中間自適應(yīng)
- 上下固定,中間自適應(yīng)(移動(dòng)端很常見(jiàn))
兩欄布局
- 左固定,右自適應(yīng)
- 右固定,左自適應(yīng)
- 上固定,下自適應(yīng)
- 下固定,上自適應(yīng)