布局分析:
第一:题面的要求当真是字面意义上这么简单吗?
第二:这道题的答案如何去写,技巧在哪里?
第三:如果我想向面试官证明我的实力和能力,这道题我能答出几种答案?
常见解决方案:
浮动和绝对定位、flex-box、网格布局、table-cell。
以下是五种解决方案的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>三栏布局</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
min-width: 550px;
}
section {
margin-top: 20px;
}
.column {
min-height: 100px;
}
</style>
</head>
<body>
<!-- 浮动三栏布局解决方案 -->
<section class="float">
<style>
.left {
float: left;
width: 300px;
background: #ffbbff;
}
.center {
background: #bfefff;
}
.right {
float: right;
width: 300px;
background: #eeee00;
}
</style>
<div class="column left">left</div>
<div class="column right">right</div>
<div class="column center">
<h2>浮动中间位置</h2>
</div>
</div>
</section>
<!-- 定位三栏布局解决方案 -->
<section class="absolute">
<style>
.absolute.column {
position: absolute;
}
.absolute.column.left {
left: 0;
width: 300px;
background-color: red;
}
.absolute.column.right {
right: 0;
width: 300px;
background-color: blue;
}
.absolute.column.right {
right: 300px;
left: 300px;
/* 宽度没写 */
background-color: yellow;
}
</style>
<div class="column left">left</div>
<div class="column right">right</div>
<div class="column center">
<h2>绝对定位解决方案</h2>
这是三栏布局绝对定位中间部分
</div>
</section>
<!-- flexbox三栏布局解决方案 -->
<section class="flexbox">
<!-- 第一步先建立分部 -->
<!-- 第二步建立容器用于装载布局 -->
<style>
.container {
display: flex;
justify-content: space-between;
}
.left {
order: 1;
width: 300px;
background: red;
}
.center {
order: 2;
flex: 1;
background: yellow;
}
.right {
order: 3;
width: 300px;
background: blue;
}
</style>
<div class="container">
<div class="column center">
<h2>flexbox布局</h2>
</div>
<div class="column left">left</div>
<div class="column right">right</div>
</div>
</section>
<!-- 表格三栏布局解决方案 -->
<section class="table">
<style>
.table.container {
width: 100%;
display: table;
}
.table.container>div {
display: table-cell;
}
.left {
width: 300px;
background: red;
}
.center {
background: yellow;
}
.right {
width: 300px;
background: blue;
}
</style>
<div class="container">
<div class="column center">
<h2>表格布局</h2>
</div>
<div class="column left">left</div>
<div class="column right">right</div>
</div>
</section>
<!-- 网格布局 -->
<section class="grid">
<style>
.grid.container {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 300px auto 300px;
}
.left {
background: red;
}
.center {
background: yellow;
}
.right {
background: blue;
}
</style>
<div class="container">
<div class="column center">
<h2>网格布局</h2>
</div>
<div class="column left">left</div>
<div class="column right">right</div>
</div>
</section>
</body>
</html>
面试引申问题:
1.每个方案的优缺点:
浮动问题:
缺点:浮动之后会脱离文档流 清除浮动处理不好会出现很多问题
优点:兼容性比较好
绝对定位问题:
缺点:因为已经脱离文档流了 那么很多子元素也会脱离文档流 可使用性差
优点:便捷
flex问题:
优点:css3新出现的方式 它就是为了解决绝对定位和浮动不足 移动端基本用的是flex布局
表格布局问题:
优点:兼容性好(支持ie8) 当flex不支持时又想解决脱离文档流的时候
缺点:较为麻烦 操作繁琐 高度会统一 但有些场景不需要同时增高
网格布局:
新技术 通过网格布局可以做很多事情 代码量也少
2.高度去掉后哪个方案不能适用了
能正常使用的是flex布局和表格布局 其他三种布局不能用