首先看一下要實現(xiàn)的效果,灰色為父元素,card隨父元素的高度自適應:

20190712150804.jpg
html:
<div class="ant-card card">
<div class="ant-card-head">Card title</div>
<div class="ant-card-body">
<p>Card content</p>
<p>Card content</p>
<p>Card content</p>
<p>Card content</p>
...
</div>
<div class="ant-card-actions">...</div>
</div>
1. flex方案
該方案不需要知道header和antions的高度,最靈活,也是首選方案
.card {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
[class*="-card-body"] {
flex: 1;
overflow: auto;
}
}
2. 不使用flex的方案
該方案的滾動條有些瑕疵,滾動范圍包含了header和actions,后面會完善
/* 滾動條不完美 */
.card {
height: 100%;
overflow: hidden;
[class*="-card-head"], [class*="-card-actions"] {
position: relative;
z-index: 10;
}
[class*="-card-head"] {
background-color: #fff;
}
[class*="-card-body"] {
margin-top: -57px;
padding-top: 57px;
padding-bottom: 48px;
margin-bottom: -48px;
height: 100%;
overflow: auto;
}
}
3. 不使用flex且滾動條完美的解決方案
.card {
position: relative;
height: 100%;
overflow: hidden;
[class*="-card-body"] {
width: 100%;
position: absolute;
top: 57px;
left: 0;
bottom: 48px;
overflow: auto;
}
[class*="-card-head"], [class*="-card-actions"] {
width: 100%;
z-index: 10;
}
[class*="-card-actions"] {
position: absolute;
left: 0;
bottom: 0;
}
}
4. 不使用flex,滾動條完美,且代碼更少的解決方案
.card {
height: 100%;
overflow: hidden;
padding-top: 57px;
padding-bottom: 48px;
> [class*="-card-head"] {
margin-top: -57px;
}
> [class*="-card-body"] {
height: 100%;
overflow: auto;
}
}
5. 使用css3的calc方案
.card {
height: 100%;
overflow: hidden;
> [class*="-card-body"] {
height: calc(100% - 57px - 48px);
overflow: auto;
}
}
總結
大家在使用時,首選flex方案,不需關心header和actions的高度,更靈活;calc方案代碼最簡潔,目前calc兼容性也很好,大部分瀏覽器都已支持;其余方案學習的意義更大。

圖片.png
最后附上測試地址,大家可以動手實踐一下。
最后的最后,這些方案都是有幸跟兩位css大神學的,想一起學習的可以留言拉你入群。