圣杯布局
刚学圣杯双飞翼布局,有点蒙,特写下来加深印象
首先要明确 圣杯布局和双飞翼布局 要解决的问题是什么?
要解决的就是让浏览器先加载最总要的那部分给客户看,我们做前端开发的时候要切合实际场景开发,合理布局,给客户最优的体验。
圣杯布局和双飞翼布局就是让浏览器先加载中间最重要的内容给客户看!!
二者特点:
- 同:两种布局都将将盒子设置为左浮动,同时在HTML中盒子加载的顺序都是中左右,给定中间容器100%的宽度让其可以随着页面宽度的变化而变化。然后再用左边距将左右容器覆盖在中间容器边上。
- 异:当将三个容器拉到同一行时,圣杯布局是调整左右容器(margin)的位置,用相对定位(relative)的方式将左右容器移出中间容器。飞翼布局是给中间容器再套一层内层容器,将内容在内层容器中显示,而不是在中间容器中。
圣杯布局
初始化圣杯布局
<div class="container">
<div class="center column"></div>
<div class="left column"></div>
<div class="right column"></div>
</div>
css
<style>
.container {
box-sizing: border-box;
height: 400px;
width: 100%;
background-color: pink;
}
.center {
background-color: red;
width: 100%;
height: 100px;
}
.left {
background-color: green;
width: 50px;
height: 100px;
}
.right {
background-color: blue;
width: 100px;
height: 100px;
}
</style>
给container设置padding
container {
box-sizing: border-box;
//左边是left宽度,right同理
padding-left: 50px;
padding-right: 100px;
height: 400px;
width: 100%;
background-color: pink;
}
到了这一步,就可以策划移动了
1、首先要让三个盒子float,那么 left和right会同行
2、把left移到左边
2.1 margin-left:-100%;
2.2 然后利用position:relative进行移动
.left {
background-color: green;
position: relative;
margin-left: -100%;
left: -50px;
width: 50px;
height: 100px;
float: left;
}
3.把right盒子移到右边
margin-left:-自身宽度px
position:relative
right:-自身宽度px
.right {
background-color: blue;
margin-left: -100px;
position: relative;
right: -100px;
width: 100px;
height: 100px;
float: left;
}
tips:上述代码中 margin-left: -100% 相对的是父元素的 content 宽度,即不包含 paddig 、
border 的宽度。
双飞翼布局
初始化代码
<style>
/* .column宽度设置和浏览器的窗口同宽,这样,main就会随着窗口的大小变化而变化了 */
.column {
width: 100%;
}
.main {
height: 100px;
margin: 0 100px 0 100px;
background-color: red;
}
.left {
height: 100px;
width: 100px;
background-color: pink;
}
.right {
height: 100px;
width: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box column">
<div class="main"></div>
</div>
<div class="left column">1</div>
<div class="right column">2</div>
接下来就可以想办法把左右两个盒子移上去了
有什么办法呢?
双翼布局不需要设置绝对定位, 只需要浮动+margin移动
//这里是有变化的代码,要让left盒子移上去,只需要浮动和margin
.column {
float: left;
width: 100%;
}
.left {
height: 100px;
width: 100px;
background-color: pink;
margin-left: -100%;
}
这里是移动了 右盒子(-自身宽度px)
margin-left: -100px;
完整代码
<style>
/* .column宽度设置和浏览器的窗口同宽,这样,main就会随着窗口的大小变化而变化了 */
.column {
float: left;
width: 100%;
}
.main {
height: 100px;
margin: 0 100px 0 100px;
background-color: red;
}
.left {
height: 100px;
width: 100px;
background-color: pink;
margin-left: -100%;
}
.right {
height: 100px;
width: 100px;
background-color: pink;
margin-left: -100px;
}
</style>
</head>
<body>
<div class="box column">
<div class="main"></div>
</div>
<div class="left column">1</div>
<div class="right column">2</div>
</body>