子div如何占满父div剩余高度

以下代码解决的问题:

  1. 子容器占满父容器剩余高度
  2. 子容器占满父容器剩余高度时,另其兄弟容器高度保持不变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<html lang="en">
<head>
<title>Flex布局,为什么items加载完毕后,height会比设置的值要小</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
.container {
display: flex;
flex-direction: column;
height: 100vh; /* 父容器占满整个视口高度 */
}
.header {
flex-shrink: 0;
height:500px; /* 如果不加flex-shrink: 0;那么items加载完毕后,height会变小*/
padding: 10px;
background-color: #f0f0f0;
border-bottom: 1px solid #ccc;
}
.content {
flex-grow: 1; /* 占满父容器剩余高度 */
overflow-y: auto; /* 当内容超出时,显示垂直滚动条 */
padding: 10px;
}
.item {
padding: 10px;
height:200px;
border-bottom: 1px solid #eee;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="header">
<h2>高度是500PX</h2>
</div>
<div class="content">
<div v-for="item in items" :key="item.id" class="item">
{{ item.text }}
</div>
</div>
</div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const { createApp } = Vue;

createApp({
data() {
return {
items: [] // 初始为空数组
};
},
mounted() {
// 模拟延迟加载数据
setTimeout(() => {
this.items = [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
{ id: 4, text: 'Item 4' },
{ id: 5, text: 'Item 5' },
{ id: 6, text: 'Item 6' },
{ id: 7, text: 'Item 7' },
{ id: 8, text: 'Item 8' },
{ id: 9, text: 'Item 9' },
{ id: 10, text: 'Item 10' }
];
}, 2000); // 延迟 2 秒渲染
}
}).mount('#app');
</script>
</body>
</html>