页面布局
这里以一道常考的面试题为例:
假设高度已知,请写出三栏布局,其中左栏,右栏各位300px,中间自适应
这道题有五种写法,分别是float,absolute,flexbox,table(老版本),grid(新技术)
这种面试题看起来简单,但一定要尽可能多的写出答案(至少三种),grid作为css3的新技术,会让面试官对你有一个好的印象,体现你对新技术和新知识的渴望
下面是代码:
<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;
}
延伸部分,分析这几种写法的优劣
- 浮动的兼容性比较好,但是会脱离文档流,处理不好会导致很多其它问题
- absolute快捷键便,缺点是会导致后续元素全部脱离文档流
- flex是移动端最完美的解决方案,但是ie8以下不支持
- 表格布局在历史上评价不高,缺点很多,现在基本已经被废弃了,优点是兼容性好
- Grid布局是新技术,而且写起来很方便,代码量也少,缺点就是浏览器的兼容问题
但是这道题到这里还不算结束,如果问题变成高度未知,这5种方法还有哪些能满足呢?
这里只有flex和table布局能继续满足要求,继续扩展下去的问题有可能问到清除浮动,BFC等相关知识点,你是否了解呢?
小结
- 语义化掌握到位,不要一路div,要使用语义化标签
- 页面布局深刻理解,清楚的写出代码
- CSS基础扎实:table,grid,flex知识点
- 思维灵活积极上进:Grid是最新技术,如果能写出来则会突显你积极上进,对新技术有渴望,知道每个方案的优缺点并加以对比,找出最符合业务场景的解决办法,才能体现出你思维灵活
- 代码书写规范,缩进,类名等等
三栏布局的变通
- 左右固定,中间自适应
- 上下固定,中间自适应(移动端很常见)
两栏布局
- 左固定,右自适应
- 右固定,左自适应
- 上固定,下自适应
- 下固定,上自适应