页面布局
前述
总所周知页面布局对于一个前端开发工程师来讲是最基础的技能之一,那对页面的布局方案又知道多少种呢
事例
假设高度已知,请写出三栏布局,其中左栏,右栏宽度各是300px,中间自适应
浮动解决方案
浮动解决方案
优点:兼容型好
缺点:浮动以后是脱离文档流,清除浮动和浮动周边的关系要处理好
<section class="layout float">
<style type="text/css">
.layout.float .left {
float: left;
width: 300px;
background: red;
}
.layout.float .right {
float: right;
width: 300px;
background: blue;
}
.layout.float .center {
background: yellow;
overflow: hidden;
}
</style>
<artice class="left-right-center">
<div class="left"></div>
<div class="right"></div>
<div class="center">
<p>浮动解决方案</p>
</div>
</artice>
</section>
绝对定位解决方案
绝对定位解决方案
优点:快捷
缺点:因为布局脱离文档流了,下面的子元素也会脱离文档流,导致该方案的可使用性是比较差的
<section class="layout absolute">
<style type="text/css">
.layout.absolute .left-right-center>div {
position: absolute;
}
.layout.absolute .left {
left: 0;
width: 300px;
background: red;
}
.layout.absolute .right {
right: 0;
width: 300px;
background: blue;
}
.layout.absolute .center {
left: 300px;
right: 300px;
background: yellow;
}
</style>
<artice class="left-right-center">
<div class="left"></div>
<div class="center">
<p>绝对定位解决方案</p>
</div>
<div class="right"></div>
</artice>
</section>
flexbox解决方案
flexbox解决方案
优点:解决上述两种方案的不足
缺点:-
<section class="layout flexbox">
<style type="text/css">
.layout.flexbox .left-right-center {
display: flex;
margin-top: 150px;
}
.layout.flexbox .left {
width: 300px;
background: red;
}
.layout.flexbox .right {
width: 300px;
background: blue;
}
.layout.flexbox .center {
flex: 1;
background: yellow;
}
</style>
<artice class="left-right-center">
<div class="left"></div>
<div class="center">
<p>flexbox解决方案</p>
</div>
<div class="right"></div>
</artice>
</section>
表格布局解决方案
表格布局解决方案
优点:兼容性好,可兼容ie8
缺点:操作繁琐,当一行中某个单元格高度超出的话,其余的也会超出
<section class="layout table">
<style type="text/css">
.layout.table .left-right-center {
display: table;
width: 100%;
min-height: 100px;
}
.layout.table .left-right-center>div {
display: table-cell;
}
.layout.table .left {
width: 300px;
background: red;
}
.layout.table .right {
width: 300px;
background: blue;
}
.layout.table .center {
background: yellow;
}
</style>
<artice class="left-right-center">
<div class="left"></div>
<div class="center">
<p>表格布局解决方案</p>
</div>
<div class="right"></div>
</artice>
</section>
网格布局解决方案
网格布局解决方案
优点:可以做一些复杂的事情,但是代码量要简化的多
缺点:-
<section class="layout grid">
<style type="text/css">
.layout.grid .left-right-center {
display: grid;
width: 100%;
/* 单元格行高 */
grid-template-rows: 100px;
/* 单元格列宽 */
grid-template-columns: 300px auto 300px;
}
.layout.grid .left {
background: red;
}
.layout.grid .right {
background: blue;
}
.layout.grid .center {
background: yellow;
}
</style>
<artice class="left-right-center">
<div class="left"></div>
<div class="center">
<p>网格布局解决方案</p>
</div>
<div class="right"></div>
</artice>
</section>