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