两栏布局:
左边定宽度 ,右边自适应
左边 float:left 左浮定宽 ,右边 overflow: hidden; 利用 BFC 清除左侧浮动对盒子的影响
页面布局:
<div class="box">
你好
</div>
<div class="box2">
秃驴飞
</div>
css:
.box {
float: left;
width: 500px;
background: pink;
}
.box2 {
overflow: hidden;
background: red;
}
三栏布局、圣杯布局、双飞翼布局
圣杯与双飞翼的区别
- 两侧宽度固定,中间自适应
- 中间部分在DOM结构上优先,方便先行渲染
- 允许三列中的任意一列成为最高列
- 只需要使用一个额外的 div 外层标签
圣杯布局
首先定义出整个布局的DOM结构,主体部分是由 box 包裹的 其中有 center 、left 、right 三个盒子,其中 center 盒子定义在最上面,来保证最先加载 center 中的内容
页面结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
/* 页面最小宽度 */
body {
min-width: 550px;
}
.box {
width: 100%;
height: 100vh;
background-color: royalblue;
padding-left: 200px;
padding-right: 150px;
float: left;
box-sizing: border-box;
}
.a {
float: left;
}
.center {
width: 100%;
height: 100%;
background-color: red;
}
.left {
width: 200px;
background-color: pink;
height: 100%;
margin-left: -100%;
position: relative;
right: 200px;
}
.right {
width: 150px;
height: 100%;
background-color: powderblue;
margin-right: -100%;
}
</style>
</head>
<body>
<div class="box">
<!-- center盒子在最上面保证最先加载center中的内容 -->
<div class="center a">秃驴飞</div>
<div class="left a"></div>
<div class="right a"></div>
</div>
</body>
</html>
得到结果
双飞翼布局:
双飞翼布局的 DOM 结构与圣杯布局的区别是用 box
仅包裹住 center
,另外将 .a
类从center
移至 box 上。
按照与圣杯布局相同的思路,首先设置各列的宽度与浮动,并且为左右两列预留出空间,以及为box
设置浮动清除:box-sizing: border-box;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
/* 页面最小宽度 */
body {
min-width: 550px;
}
.box {
width: 100%;
height: 100vh;
background-color: royalblue;
box-sizing: border-box;
}
.a {
float: left;
}
.center {
margin-left: 200px;
margin-right: 150px;
background-color: red;
}
.left {
width: 200px;
background-color: pink;
height: 100px;
margin-left: -100%;
}
.right {
width: 150px;
height: 200px;
background-color: powderblue;
margin-left: -150px;
}
</style>
</head>
<body>
<div class="box a">
<div class="center">秃驴飞</div>
</div>
<div class="left a"></div>
<div class="right a"></div>
</body>
</html>
总结:
通过对圣杯布局和双飞翼布局的结构可以看出,圣杯布局在DOM结构上显得更加直观和自然,且在日常开发过程中,更容易形成这样的DOM结构;而双飞翼布局在实现上由于不需要使用定位,所以更加简洁,且允许的页面最小宽度通常比圣杯布局更小。
flex布局
flex布局相对于以上两个布局更加简单,页面结构与圣杯布局相同
<div class="box">
<!-- center盒子在最上面保证最先加载center中的内容 -->
<div class="center a">秃驴飞</div>
<div class="left a"></div>
<div class="right a"></div>
</div>
css
.box {
height:100vh;
display: flex;
}
.center {
height:100%;
flex: 1;
}
.left {
height:100%;
flex: 0 0 200px;
order: -1;
}
.right {
height:100%;
flex: 0 0 150px;
}