如何使用Flexbox将卡片组件内的按钮固定在底部?
问题描述
我用HTML和CSS搭建了基础页面,并用Flexbox实现了自定义卡片组件。但卡片内的「Read More」按钮无法和其他卡片的按钮对齐到底部(如图所示):

请问仅通过Flexbox修改代码,如何让所有「Read More」按钮固定在卡片底部,保持同一水平线?
现有代码如下:
CSS代码
.container { max-width: 1200px; margin: 0 auto; } .main-content { display: flex; flex-wrap: wrap; justify-content: space-between; } img { max-width: 100%; display: block; } .entry { flex: 0 0 calc(33.33% - 1rem); margin-bottom: 1rem; background-color: white; } .entry .content { padding: 1rem; text-align: center; text-transform: uppercase; } h3 { margin: 0; font-weight: 700; } .content h3 { font-size: 0.9rem; line-height: 1.5rem; } .content span { color: #db008d; } .button { background-color: dodgerblue; color: white; text-decoration: none; padding: .6rem 2rem; margin-top: 1rem; display: inline-block; } .content { /*What to write here ?? */ }
HTML代码
<main class="main-content"> <article class="entry"> <img src="img/01.jpg" alt="entry image"> <div class="content"> <h3>Tips for Saving Money in your Next Travel</h3> <p>Published on: <span>July 19th, 2019</span></p> <p>By: <span>The Travel Blog</span></p> <a href="#" class="button">Read More</a> </div> </article> <article class="entry"> <img src="img/02.jpg" alt="entry image"> <div class="content"> <h3>The Complete Guide for Traveling</h3> <p>Published on: <span>July 19th, 2019</span></p> <p>By: <span>The Travel Blog</span></p> <a href="#" class="button">Read More</a> </div> </article> <article class="entry"> <img src="img/03.jpg" alt="entry image"> <div class="content"> <h3>Ultimate Guide to Take the best Pictures</h3> <p>Published on: <span>July 19th, 2019</span></p> <p>By: <span>The Travel Blog</span></p> <a href="#" class="button">Read More</a> </div> </article> </main>
解决方案
只需对两处CSS进行修改,完全基于Flexbox实现按钮对齐:
- 修改
.entry为垂直方向的Flex容器,让卡片内部元素(图片+内容区)垂直排列,同时确保内容区能自动填充剩余空间:
.entry { flex: 0 0 calc(33.33% - 1rem); margin-bottom: 1rem; background-color: white; display: flex; flex-direction: column; }
- 修改
.content为垂直方向的Flex容器,通过justify-content: space-between让内容分布在容器上下,把按钮推到底部,同时保留原有的文本对齐和内边距:
.content { display: flex; flex-direction: column; justify-content: space-between; padding: 1rem; text-align: center; text-transform: uppercase; flex-grow: 1; /* 让内容区填满卡片剩余高度 */ }
另外,建议调整按钮的外边距,确保按钮始终贴底:
.button { background-color: dodgerblue; color: white; text-decoration: none; padding: .6rem 2rem; margin-top: auto; /* 替换原有的margin-top:1rem */ display: inline-block; }
这样修改后,所有卡片的「Read More」按钮会自动对齐到卡片底部,保持同一水平线,同时不影响其他内容的布局。
内容的提问来源于stack exchange,提问作者Balaji KR
相关产品推荐
相关产品推荐

