做卡片時經(jīng)常會遇到卡片內(nèi)容不同颤枪,導(dǎo)致高度撐開不相渤昌。如果此時想要高度相同的話可能會有種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;
}
上邊代碼效果其實也過的去缝其,截圖如下:
image.png
加上如下css 代碼:
/* Added code */
.gallery-grid {
...
grid-auto-rows: 1fr;
}
展示結(jié)果如下:
image.png
這個示例非常簡單挎塌,實際工作中格子內(nèi)可能會有多個元素,按鈕内边,圖片什么榴都,所以格式內(nèi)可以再使用 flex 布局,代碼如下:
/* CSS Flexbox */
.grid-box {
display: flex;
flex-flow: column nowrap;
...
}
只這樣還是不夠假残,因為元素的高度可能不一樣缭贡,所以需要某些需要的元素上加上
/* Place elements at the bottom */
.m-top {
margin-top: auto;
}
如上,關(guān)鍵代碼都有了辉懒。
這里貌似不能上傳代碼阳惹,所以示例請看原文