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

如何正确排布flex容器内子元素以实现预期布局效果?

问题根源

  • 你直接将图片、标题、p标签、评分块全部作为flex容器的直接子元素,同时开启了flex-wrap: wrap,容器宽度不足时p标签会被挤压到下一行,导致错位
  • 评分块设置了flex: 1 1 auto,flex-shrink为1时会被自动压缩,你设定的20px宽度远小于"8.3/10"的实际内容宽度,就会出现内容裁切
  • flex布局中子元素的float属性无效,属于冗余代码

修复方案

调整HTML结构,将标题和p标签包裹为一个独立的中间内容区块,让flex容器只有三个直接子项:左侧图片、中间内容区、右侧评分块,同时调整对应flex属性避免元素压缩。

完整修改后代码

HTML

<div class="preview">
  <img src="img/god_of_war.jpg" id="1">
  <!-- 新增中间内容包裹层 -->
  <div class="content">
    <h5>Assemble Your Squad and <br>Join the Battle</h5>
    <p>Nintendo Wii, PS4, XBox 360</p>
  </div>
  <div class="score">8.3/10</div>
</div>

CSS

.preview {
  display: flex;
  /* 调整为两端对齐,不需要居中 */
  justify-content: space-between;
  cursor: pointer;
  align-items: center;
  /* 关闭换行,避免元素被挤到下一行 */
  /* flex-wrap: wrap; */
  width: 100%;
  height: 150px;
  background-color: #232323;
}

.preview img {
  /* 去掉无效的float */
  /* float: left; */
  /* 固定图片尺寸,不缩放 */
  flex: 0 0 auto;
  margin-left: 10px;
  width: 80px;
  height: 80px;
  object-fit: contain;
}

/* 新增中间内容区样式 */
.preview .content {
  flex: 1;
  margin: 0 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.preview h5 {
  color: #fff;
  text-align: left;
  line-height: 25px;
  margin: 0 0 8px 0;
}

.preview p {
  color: #a1a5a5;
  text-align: left;
  font-size: 10px;
  margin: 0;
}

.score {
  display: inline-block;
  text-align: center;
  margin-right: 10px;
  /* 固定评分块尺寸,不缩放 */
  flex: 0 0 auto;
  /* 调宽宽度适配内容 */
  width: 45px;
  height: 30px;
  /* 新增行高让文字垂直居中 */
  line-height: 30px;
  background-color: #20d8da;
  color: #fff;
  font-family: "Open Sans", sans-serif;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:39:03