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

Flex布局下flex-basis超出容器边界的适配问题咨询

视频容器自适应布局解决方案

问题核心

容器内最多9个视频,要求每行最多3个、保持16/9宽高比,当前视频超出容器高度,需在不设置视频固定高度的前提下实现自适应容纳。

解决方案代码

修改后的CSS

html, body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

.page {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.container {
  height: calc(100% - 12rem);
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 固定每行3个视频 */
  gap: 12px; /* 统一行列间距 */
  width: 100%;
  background-color: #444;
  padding: 0 12px; /* 可选:避免视频贴容器边缘 */
}

.video {
  aspect-ratio: 16 / 9;
  background-color: gray;
  /* 计算最大高度:容器高度减去2个行间距,再均分3行 */
  max-height: calc((100% - 24px) / 3);
  width: 100%;
  /* 若为真实视频,添加以下属性保证比例 */
  /* object-fit: contain; */
}

保持原HTML不变

<div class="page">
  <div class="container">
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
      <div class="video"></div>
  </div>
</div>

关键修改说明

  1. 替换Flex为Grid布局:通过grid-template-columns: repeat(3, 1fr)直接固定每行3个视频,布局逻辑更精准,避免Flex换行的不确定性。
  2. 计算视频最大高度:用max-height: calc((100% - 24px) / 3)确保3行视频加2个间距的总高度刚好适配容器,彻底解决溢出问题。
  3. 依赖aspect-ratio自动适配宽度:视频保持16/9比例,宽度随列宽自动调整,无需手动设置固定宽高。

内容的提问来源于stack exchange,提问作者Mr.Smithyyy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:41:08