圣杯布局和双飞翼布局作为前端的经典布局,主要用于 PC 端项目的布局
主要涉及的知识点是: float 布局 和 负边距
在浏览器的渲染过程中,元素节点的排布是从上到下,从左至右,遇到空间不足就会换行排列,这是文档流中元素的排列的基本特点。
float 布局: 当元素添加了 float
的属性时,会使得该元素会被移出正常的文档流,然后向左或者向右平移,一直平移直到碰到了所处的容器的边框,或者碰到另外一个浮动的元素
负边距:
负边距的知识点
margin-left 为负: 左移
margin-right 为负:左拉
效果图
*{
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
text-align: center;
background: #eee;
}
.header {
height: 48px;
background: lightblue;
}
.footer {
clear: both;
height: 60px;
background: lightgray;
}
.container {
height: 200px;
padding: 0 300px;
}
.center {
float: left;
width: 100%;
height: 100%;
background: lightgreen;
}
.left {
position: relative;
right: 300px;
float: left;
width: 300px;
height: 100%;
background: yellow;
margin-left: -100%;
}
.right {
float: left;
width: 300px;
height: 100%;
background: pink;
margin-right: -100%;
}
<div class="header">
this is header
</div>
<div class="container">
<div class="center">center</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
<div class="footer">
this is footer
</div>
- container 容器设置 padding 给 left、right 元素留出空间
- center、left、right 都要左浮动
- left 元素 margin-left: -100%; 这个100%指的是父级容器的 100% 的宽度。可以理解成:在文档的流式布局中,left排在center之后,center 元素(块元素)占满父容器宽度,left排在center后面由于同一行没有剩余空间导致换行了。-100%(父容器)的宽度会导致 left 元素顶格排列;
- position: relative; right: 300; 使得 left 元素的起点从 right: 300px 开始;正好占用 container 的 padding-left 的 300px 空间;
- right 元素,margin-right: -300px; 会导致 right 元素后续元素的排列认为 right 元素没有宽度