html各种布局整理
👉👉本文共904字📘
读完共需4分钟⌚
¶传统布局
¶1.圣杯布局
圣杯布局就是两边顶宽,中间自适应的三栏布局,中间栏要放在文档流前面一优先渲染。
很多经典的网页就是这种布局,应用场景很多。
先看下圣杯布局的dom结构。
<section class="layout grail">
<h1>圣杯布局</h1>
<article class="left-center-right">
<div class="center">
</div>
<div class="left"></div>
<div class="right"></div>
</article>
</section>
注意:
这里center 要放在第一个,就是 中 左 右 的顺序。
把“中”放在第一位,是为了首先加载“中”的内容,并且“中”的宽度是自适应的。
有两种方法,第一种是给左右设置负的margin-left,点击查看负margin的原理。
简单来说,给左 设置 margin-left:-100%.右设置margin-left:-300px;就把这两个box 拉回上一行,然后给父容器设置左右padding 为 左右的宽度,不过此时左右又受到padding的影响,向中间挤。此时然后再用相对定位把左右调整一下。
css代码如下。
.layout.grail .left-center-right {
padding: 0 300px;
min-width: 304px;
}
.layout.grail .left-center-right>div {
float: left;
min-height: 100px;
}
.layout.grail .center {
background: yellow;
width:100%;
}
.layout.grail .left {
margin-left: -100%;
width: 300px;
background: red;
position: relative;
left: -300px;
}
.layout.grail .right {
margin-left: -300px;
width: 300px;
background: blue;
position: relative;
right: -300px;
}
第二种是给父容器设置
overflow: hidden;
box-sizing: border-box;
padding: 0 300px 0 300px;
圣杯布局的优点:
- 主列率先加载
- 允许任何列是最高的
- DOM结构简单
缺点:
- 和双飞翼布局相比CSS样式较为复杂
¶2.双飞翼布局
双飞翼布局源自淘宝UED,第一步和圣杯布局一样,浮动三列,给左右两列设置负外边距;同样会覆盖主列main,双飞翼布局的做法是在主列main后面添加了一个宽度为100%的div,再设置主列main的左右边距,代码如下:
<div class="wrap">
<div class="main"></div>
</div>
<div class="left"></div>
<div class="right"></div>
.wrap{
float: left;
width: 100%;
}
.main{
height: 200px;
margin-left: 110px;
margin-right: 210px;
background-color: #01549b;
}
.left{
float: left;
height: 200px;
width: 100px;
margin-left: -100%;
background-color: #bd4147;
}
.right{
float: left;
height: 200px;
width: 200px;
margin-left: -200px;
background-color: #419641;
}
优点:
- 率先加载主列main
- 允许任何列是最高的
- CSS样式简单
缺点:
- 和圣杯布局相比DOM结构较为复杂
¶现代布局
¶1.flex 布局
Flex 布局教程:语法篇 阮一峰老师翻译的css-tricks上的文章。
原文地址:A Complete Guide to Flexbox
用Flex布局实现中间自适应,两边固定,很简单。
dom节点
<header>
header
</header>
<div class="box">
<div class="left">
left
</div>
<div class="center">
center
</div>
<div class="right">
right
</div>
</div>
<footer>
footer
</footer>
css代码
.box {
display: flex;
justify-content: space-between;
}
.left {
width:300px;
background-color: aquamarine;
}
.center {
background-color: black;
width: 100%;
}
.right{
width: 350px;
background-color: blue;
}
只要把父的dom的display设置为flex就行了。
¶2.grid 布局
Grid布局指南 也是一篇译文。
<div class='grid'>
<div class="left">
left
</div>
<div class='rigth'>
right
</div>
</div>
.grid{
display: grid;
grid-template-columns: 200px auto;
grid-template-rows: 200px;
}
资料和代码来源: