flex弹性布局
弹性布局通过给给容器添加display: flex;属性使其变成弹性容器。从而通过改变justify-content属性的值来调整距离的分配。
弹性布局的优点非常明显,相对于繁琐的浮动布局,flex布局代码更简洁,更容易上手,根据flex规则很容易达到某个布局效果。 弹性布局在网页中实现快速分配比例,盒子快速对齐优势很大,因为通过简单的几个属性就可以实现,进而减少我们设置具体值。然而其缺点也一目了然,其兼容性并不兼容大多数的老版浏览器,所以其一般使用在移动端的布局。
<!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;
}
header,
body>div,
section,
footer {
margin: 10px auto;
}
header {
background-color: antiquewhite;
width: 100%;
height: 50px;
}
nav {
background-color: antiquewhite;
height: 50px;
}
nav,
section,
body>div,
footer>div {
width: 1200px;
}
.baner {
height: 200px;
background-color: antiquewhite;
}
section>div:nth-of-type(1),
section>div:nth-of-type(2) {
margin: 10px 0;
display: flex;
justify-content: space-between;
}
section>div:nth-of-type(1) div {
width: 290px;
height: 200px;
background-color: antiquewhite;
}
section>div:nth-of-type(2) div {
width: 290px;
height: 400px;
background-color: antiquewhite;
}
footer {
width: 100%;
height: 100px;
background-color: antiquewhite;
}
</style>
</head>
<body>
<header>
<nav></nav>
</header>
<div class="baner">
</div>
<section>
<div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</section>
<footer>
<div></div>
</footer>
</body>
</html>
传统浮动布局
浮动布局上手难度略有增加,代码繁琐度也拉高了,然而因为其良好的兼容性仍然是目前PC端网页布局的一种主流布局方式。
浮动布局的难点主要在于其浮动元素对于后续元素的影响,所以增加的清除浮动的步骤。
<!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;
}
header,
body>div,
section,
footer {
margin: 10px auto;
}
header {
background-color: antiquewhite;
width: 100%;
height: 50px;
}
nav {
background-color: antiquewhite;
height: 50px;
}
nav,
section,
body>div,
footer>div {
width: 1200px;
}
.baner {
height: 200px;
background-color: antiquewhite;
}
section>div:nth-of-type(1),
section>div:nth-of-type(2) {
margin: 10px 0;
overflow: hidden;
}
section>div:nth-of-type(1) div {
width: 22%;
height: 200px;
float: left;
background-color: antiquewhite;
}
section>div:nth-of-type(2) div {
width: 22%;
height: 400px;
float: left;
background-color: antiquewhite;
}
.ko {
margin-right: 4%;
}
footer {
width: 100%;
height: 100px;
background-color: antiquewhite;
}
</style>
</head>
<body>
<header>
<nav></nav>
</header>
<div class="baner">
</div>
<section>
<div>
<div class="ko"></div>
<div class="ko"></div>
<div class="ko"></div>
<div></div>
</div>
<div>
<div class="ko"></div>
<div class="ko"></div>
<div class="ko"></div>
<div></div>
</div>
</section>
<footer>
<div></div>
</footer>
</body>
</html>