页面布局
目的:假设高度以知,请写出三栏布局,其中左栏、右栏宽度各为100px,中间自适应。
- 利用浮动
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 100px;
}
.left {
float: left;
width: 100px;
background-color: red;
}
.right {
float: right;
width: 100px;
background-color: yellow;
}
.center {
background-color: pink;
}
</style>
</head>
<body>
<div>
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
</body>
</html>
缺点就是主要内容无法最先加载,当页面内容较多时会影响用户体验。
- 利用绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
position: relative;
}
.container div {
height: 100px;
}
.left {
position: absolute;
left: 0;
top: 0;
width: 100px;
background-color: red;
}
.right {
position: absolute;
right: 0;
top: 0;
width: 100px;
background-color: yellow;
}
.center {
position: absolute;
/*同时指定 left 和 right 可以使其撑开*/
left: 100px;
right: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<div class="center">123</div>
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
- flex 的写法
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: flex;
}
.container div {
height: 100px;
}
.left {
width: 100px;
background-color: red;
}
.right {
width: 100px;
background-color: yellow;
}
.center {
flex-grow: 1;
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
</html>
- 关于表格布局
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
width: 100%;
display: table;
}
.container div {
height: 100px;
display: table-cell;
}
.left {
width: 100px;
background-color: red;
}
.right {
width: 100px;
background-color: yellow;
}
.center {
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="center">123</div>
<div class="right"></div>
</div>
</body>
</html>
- 网格布局
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: grid;
width: 100%;
grid-template-rows: 100px;
grid-template-columns: 100px auto 100px;
}
.left {
background-color: red;
}
.right {
background-color: yellow;
}
.center {
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="center">123</div>
<div class="right"></div>
</div>
</body>
</html>