做卡片時(shí)經(jīng)常會(huì)遇到卡片內(nèi)容不同,導(dǎo)致高度撐開(kāi)不相。如果此時(shí)想要高度相同的話可能會(huì)有種hacker代碼,下面提供一種使用grid 和 flex 布局結(jié)合的處理方法,供參考。
原文地址: Equal Height Boxes with CSS Grid Layout
外部布局使用gird, 格子內(nèi)部使用 flex,大致代碼:
<!-- HTML結(jié)構(gòu) -->
<div class="auto-grid">
<div class="grid-box">
...
</div>
</div>
CSS 代碼:
/* First the Grid */
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
grid-gap: 1.5rem;
justify-items: center;
margin: 0;
padding: 0;
}
上邊代碼效果其實(shí)也過(guò)的去,截圖如下:

image.png
加上如下css 代碼:
/* Added code */
.gallery-grid {
...
grid-auto-rows: 1fr;
}
展示結(jié)果如下:

image.png
這個(gè)示例非常簡(jiǎn)單,實(shí)際工作中格子內(nèi)可能會(huì)有多個(gè)元素,按鈕,圖片什么,所以格式內(nèi)可以再使用 flex 布局,代碼如下:
/* CSS Flexbox */
.grid-box {
display: flex;
flex-flow: column nowrap;
...
}
只這樣還是不夠,因?yàn)樵氐母叨瓤赡懿灰粯?,所以需要某些需要的元素上加?/p>
/* Place elements at the bottom */
.m-top {
margin-top: auto;
}
如上,關(guān)鍵代碼都有了。
這里貌似不能上傳代碼,所以示例請(qǐng)看原文