13、场景题
题目
三个 div: div1:width:100px div2:auto height:800px div3:width:100px 如何实现 div1、div3 高度自适应
参考答案
Flexbox
弹性布局
DETAILS
<!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>
.container {
display: flex;
/* 启用弹性布局 */
align-items: stretch;
/* 默认值,子项高度拉伸至容器高度 */
}
.div1,
.div3 {
width: 100px;
/* 固定宽度 */
background: #f0f0f0;
}
.div2 {
height: 800px;
/* 固定高度 */
flex: 1;
/* 占据剩余空间 */
background: #e0e0e0;
}
</style>
</head>
<body>
<div class="container">
<div class="div1">div1</div>
<div class="div2">div2(固定高度 800px)</div>
<div class="div3">div3</div>
</div>
</body>
</html>
Grid
网格布局
<!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>
.container {
display: grid;
grid-template-columns: 100px 1fr 100px;
/* 三列布局 */
grid-template-rows: 800px;
/* 固定行高 */
}
.div1,
.div3 {
background: #f0f0f0;
}
.div2 {
background: #e0e0e0;
}
</style>
</head>
<body>
<div class="container">
<div class="div1">div1</div>
<div class="div2">div2(固定高度 800px)</div>
<div class="div3">div3</div>
</div>
</body>
</html>