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

如何让上下排列的两个div随内容动态保持等高?

解决方案

要实现底部div高度由内容决定、顶部div同步等高的效果,CSS Grid是最简洁的纯CSS方案,无需JavaScript。

问题分析

你之前的flex布局思路中,flex-grow:1是让元素填充容器剩余空间,而非匹配另一元素的高度;设置height:50%则依赖容器有明确高度,无法随内容动态调整,所以达不到预期效果。

实现代码

CSS

.container {
  display: grid;
  grid-template-rows: 1fr 1fr; /* 强制两行高度完全相等 */
}

.box {
  width: 100%;
}

.b1 {
  background-color: red;
}

.b2 {
  background-color: orange;
}

HTML

<div class="container">
  <div class="box b1">One</div>
  <div class="box b2">
    DIV B Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>
</div>

原理说明

  • display: grid将容器转为网格布局
  • grid-template-rows: 1fr 1fr定义两行,每行占比相等,网格容器的高度会自动适配内容最多的子元素,两行高度同步等于这个最大高度
  • 当屏幕宽度缩小导致底部div文本换行、高度增加时,网格容器高度随之调整,顶部div的高度也会同步升高,完全满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:07:31