如何用CSS实现每行并列显示两个尺寸一致的国家卡片
解决方案
问题分析
你当前的代码有三个核心问题导致无法每行显示两个卡片:
- 容器未正确包裹卡片:HTML里的
.country元素没有放在.country-container容器内,flex布局的样式完全没生效。 - 卡片宽度计算错误:
calc(50% - 1em)没有考虑卡片左右各1em的margin,两个卡片总宽度会超过容器,触发换行。 - 国旗图片未限制尺寸:图片过宽会撑大卡片,导致卡片尺寸不一致。
修复步骤及代码
1. 修正HTML结构,把卡片放入容器
确保所有.country元素都包裹在.country-container里,这样flex布局才能生效。
2. 调整卡片宽度计算
把卡片的flex值改为0 1 calc(50% - 2em),抵消左右各1em的margin,保证两个卡片刚好填满容器宽度。
3. 限制国旗图片宽度
给.flag设置max-width: 100%,确保图片不会超出卡片宽度,同时保持比例。
完整修复代码
CSS
.country-container { display: flex; flex-wrap: wrap; gap: 2em; /* 用gap替代margin,更简洁的间距控制 */ padding: 0 1em; /* 给容器加左右内边距,避免卡片贴边 */ } .country { flex: 0 1 calc(50% - 1em); /* 因为gap是2em,每个卡片占50%减去一半的gap */ display: flex; flex-direction: column; align-items: center; border: 3px solid #212020; padding: 1em; text-align: center; background-color: beige; box-sizing: border-box; /* 确保padding和border不会额外增加宽度 */ } .flag { max-width: 100%; /* 限制图片最大宽度为卡片宽度 */ height: auto; /* 保持图片比例 */ } .country h2 { margin: 5px 0; } .wiki-link { display: block; text-align: center; margin-top: 5px; }
HTML
<div class="country-container"> <div class="country"> <img class="flag" src="country_flags/ws.png" alt="Flag of Samoa"/> <h2>Samoa</h2> <p>Currency: Euros (EUR)</p> <p>Regions: Atua, Fa'asaleleaga, Tuamasaga</p> <a class="wiki-link" href="https://en.wikipedia.org/wiki/Samoa" target="_blank">Wikipedia</a> </div> <div class="country"> <img class="flag" src="country_flags/pk.png" alt="Flag of Pakistan"/> <h2>Pakistan</h2> <p>Currency: Rupee (PKR)</p> <p>Regions: Azad Jammu and Kashmir, Balochistan, Gilgit-Baltistan, Islamabad, Khyber Pakhtunkhwa, Punjab, Sindh</p> <a class="wiki-link" href="https://en.wikipedia.org/wiki/Pakistan" target="_blank">Wikipedia</a> </div> </div>
额外说明
- 用
gap替代margin可以避免margin折叠问题,更方便控制卡片间的间距。 - 添加
box-sizing: border-box确保卡片的padding和border不会影响宽度计算,保证尺寸一致。 - 限制图片宽度后,所有卡片的高度会根据内容自动调整,如果需要强制所有卡片高度一致,可以给
.country添加flex: 1或者min-height属性。
内容的提问来源于stack exchange,提问作者Shaz
相关产品推荐
相关产品推荐

