You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Flex布局下的卡片保持比例,适配各类屏幕?

解决Flex布局中卡片比例失调与溢出问题

核心修改要点

  • 给Flex容器开启换行:在#cards中添加flex-wrap: wrap,确保屏幕空间不足时卡片自动换行。
  • 固定卡片的基础尺寸与比例:用flex: 0 0 18rem锁定卡片的基础宽度(不会被拉伸/压缩),搭配aspect-ratio: 18/16维持宽高比例,同时设置max-width: 100%适配小屏幕。
  • 避免内边距导致的尺寸溢出:给所有元素添加box-sizing: border-box,让padding和border包含在元素的宽高计算内,防止按钮或卡片内容溢出。
  • 卡片高度改用min-height替代固定height,确保内容较多时不会被裁切。

修改后的完整代码

CSS部分

/* 全局盒模型重置,避免padding影响尺寸计算 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

#cards {
  display: flex;
  justify-content: center;
  gap: 3%;
  margin: 0 auto 10vw auto;
  width: 75%;
  flex-wrap: wrap; /* 新增:开启换行 */
}

.card {
  display: flex;
  flex-direction: column;
  padding: 1rem 2rem 3rem 2rem;
  flex: 0 0 18rem; /* 锁定基础宽度,不拉伸不压缩 */
  max-width: 100%; /* 小屏幕下不超出容器 */
  aspect-ratio: 18/16; /* 固定宽高比例 */
  align-items: center;
  justify-content: space-between;
  border-radius: 2vh;
  background-color: #00BFFF;
  border: none;
  margin-bottom: 2rem; /* 换行后增加垂直间距 */
}

.card .content {
  text-align: center;
  font-size: 1.8rem;
  font-weight: 700;
}

.card .button {
  width: 100%;
  border-radius: 2vh;
  text-decoration: none;
  border: none;
  background-color: purple;
  color: white;
  font-weight: 700;
  padding: 1em 1.3em;
  text-align: center;
  cursor: pointer;
}

HTML部分

<div id="cards">
  <div class="card">
    <div class="content">
      <p>
        Hello, World
        <br />
        From Card #1
      </p>
    </div>
    <a class="button" href="#">Link Button</a>
  </div>
  <div class="card">
    <div class="content">
      <p>
        Hello, World
        <br />
        From Card #2
      </p>
    </div>
    <a class="button" href="#">Link Button</a>
  </div>
  <div class="card">
    <div class="content">
      <p>
        Hello, World
        <br />
        From Card #3
      </p>
    </div>
    <a class="button" href="#">Link Button</a>
  </div>
  <div class="card">
    <div class="content">
      <p>
        Hello, World
        <br />
        From Card #4
      </p>
    </div>
    <a class="button" href="#">Link Button</a>
  </div>
</div>

额外说明

  • aspect-ratio属性可以精准控制卡片的宽高比例,替代固定height,适配不同屏幕尺寸;
  • flex: 0 0 18rem确保卡片在Flex布局中保持固定的基础宽度,不会被容器挤压或拉伸;
  • 全局box-sizing: border-box是前端布局的常用最佳实践,避免内边距和边框导致的尺寸计算混乱。

内容的提问来源于stack exchange,提问作者pileup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:10:13