01前端/CSS 每列高度自适应父元素高度

让每列高度自适应父元素高度,如果父元素高度固定直接用百分比就行,但父元素高度是 auto(通过子元素计算)的话就得用下面的方法了。

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
<!DOCTYPE html>
<style>
.left {
height: 200px;
width: 200px;
background: aqua;
}

.right {
border-radius: 16px;
width: 200px;
background: violet;
}
</style>

<h1>flex</h1>
<div style="display: flex;">
<div class="left">200px</div>
<div class="right" style="align-self: stretch;">adaptive</div>
</div>

<h1>table</h1>
<div style="display: table;">
<div class="left" style="display: table-cell;">200px</div>
<div class="right" style="display: table-cell;">adaptive</div>
</div>

<h1>position</h1>
<div
style="
position: relative;
width: 400px;"
>
<div class="left">200px</div>
<div
class="right"
style="
position: absolute;
top: 0;
right: 0;
height: 100%;"
>
adaptive
</div>
</div>

<h1>float + padding + margin</h1>
<p>这种方式只能让背景色延伸到父元素边界</p>
<div style="overflow: hidden;">
<div class="left" style="float: left">200px</div>
<div
class="right"
style="
float: left;
padding-bottom: 9999px;
margin-bottom: -9999px;"
>
adaptive
</div>
</div>