如何实现div卡片底部h2文本居中且距底边距离统一
解决方案
问题根源有两点:一是同一行的卡片高度没有统一对齐,二是文本容器未设置为垂直弹性布局,导致margin-top: auto没有生效。按以下要求修改CSS即可实现所有卡片底部副标题距离底边统一、居中对齐的效果:
/* 仅需修改/新增以下标注的属性,原有其他属性保留即可 */ .courseContainer{ display: flex; justify-content: center; flex-direction: row; align-items: stretch; /* 新增:让同一行所有卡片高度自动对齐到最高的卡片 */ } .courseCard{ display: flex; padding: 30px; margin-left: 5%; margin-right: 5%; margin-top: 40px; margin-bottom: 40px; width: 500px; height: auto; border-radius: 18px; background: #800400; box-shadow: 5px 5px 15px rgba(0,0,0,0.9); text-align: center; justify-content: center; font-family: "Source Sans Pro", sans-serif; } .courseText{ font-family: "Source Sans Pro",sans-serif; color: white; display: flex; /* 新增:设置为弹性布局 */ flex-direction: column; /* 新增:子元素垂直排列 */ width: 100%; /* 新增:占满卡片宽度 */ } .courseHeader{ font-weight:900; } .courseDescription{ margin-top: 20px; /* 修改:把百分比改为固定像素值,避免边距随卡片高度变化 */ } .timeLength{ margin-top: auto; /* 保留:自动把副标题推到容器底部 */ margin-bottom: 0; /* 修改:固定底部边距,可根据需求调整数值 */ }
修改后所有同一行的卡片高度会自动统一,副标题会始终固定在距离底部统一边距的位置,且自带居中对齐效果。
内容的提问来源于stack exchange,提问作者Nick Johnson
相关产品推荐
相关产品推荐

