题目:假设高度已知,请写出三栏布局,其中左栏、右栏宽度客为300px,中间自适应。
各种解决方案
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>页面布局</title>
<style>
html * { padding: 0; margin: 0; }
.layout article div {
min-height: 100px;
}
/* 浮动解决方案 */
.layout.float .left {
float: left;
width: 300px;
background: red;
}
.layout.float .right {
float: right;
width: 300px;
background: blue;
}
.layout.float .center {
background: yellow;
}
/* 绝对定位解决方案 */
.layout.absolute article{
height: 100px;
}
.layout.absolute article div {
position: absolute;
}
.layout.absolute .left {
left: 0;
width: 300px;
background: red;
}
.layout.absolute .center {
left: 300px;
right: 300px;
background: yellow;
}
.layout.absolute .right {
right: 0;
width: 300px;
background: blue;
}
/* flexbox解决方案 */
.layout.flexbox article {
display: flex;
}
.layout.flexbox .left {
width: 300px;
background: red;
}
.layout.flexbox .center {
flex: 1;
background: yellow;
}
.layout.flexbox .right {
width: 300px;
background: blue;
}
/* table解决方案 */
.layout.table article {
width: 100%;
display: table;
height: 100px;
}
.layout.table article > div {
display: table-cell;
}
.layout.table .left {
width: 300px;
background: red;
}
.layout.table .center {
background: yellow;
}
.layout.table .right {
width: 300px;
background: blue;
}
/* css grid布局解决方案 */
.layout.grid article {
display: grid;
width: 100%;
grid-template-rows: 100px; /* 可省略 */
grid-template-columns: 300px 1pr 300px;
}
.layout.grid .left {
background: red;
}
.layout.grid .center {
background: yellow;
}
.layout.grid .right {
background: blue;
}
</style>
</head>
<body>
<h1>浮动解决方案</h1>
<section class="layout float">
<article class="left-right-center">
<div class="left">左</div>
<div class="right">右</div>
<div class="center">中</div>
</article>
</section>
<h1>绝对定位解决方案</h1>
<section class="layout absolute">
<article class="left-center-right">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</article>
</section>
<h1>flex解决方案</h1>
<section class="layout flexbox">
<article class="left-center-right">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</article>
</section>
<h1>table解决方案</h1>
<section class="layout table">
<article class="left-center-right">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</article>
</section>
<h1>网格布局解决方案</h1>
<section class="layout grid">
<article class="left-center-right">
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</article>
</section>
</body>
</html>
查看效果:https://jsbin.com/xaxujoyisa/1/edit?html,output
优缺点、比较、不定高、兼容性?
浮动:兼容性好
绝对定位:快捷,脱离文档流,可使用性差
flex布局:完美,移动端使用较多,ie低版本不兼容
表格布局:兼容性好,历史原因不建议使用
网格布局:新技术,代码少
不定高的情况下,flex布局和表格布局可以使用
网格布局
CSS网格布局引入了二维网格布局系统,可用于布局页面主要的区域布局或小型组件。查阅