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

使用Flexbox无法让两个子Div各占父容器一半空间的问题

问题分析

你的问题核心在于父容器#searchbarWindow未设置明确高度——Flex布局中flex:1的作用是让子元素分配父容器的可用空间,但如果父容器高度完全由内部内容撑开,子元素就没有额外空间可以均分,导致红色div仅包裹自身内容、视觉上占比更大。

解决方案

给父容器添加固定高度(比如基于视口的百分比高度),同时可补充宽度优化窗口形态,修改后的代码如下:

#opacScreen {
  display: block;
  z-index: 35;
  position: fixed;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
  height: 100vh;
  width: 100vw;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

#searchbarWindow {
  z-index: 40;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: var(--main-color);
  display: flex;
  flex-direction: column;
  /* 新增:给父容器设置明确高度和宽度 */
  height: 80vh;
  width: 60vw;
}

#divsearchbar {
  background-color: red;
  flex: 1;
  /* 可选优化:让内部输入区域垂直居中 */
  display: flex;
  align-items: center;
  padding: 0 1rem;
}

#displaysearch {
  background-color: green;
  flex: 1;
  /* 可选优化:让提示文字居中显示 */
  display: flex;
  align-items: center;
  justify-content: center;
}
关键说明
  • 父容器必须有明确高度,子元素的flex:1才能按1:1的比例分配空间,示例中用80vh让窗口占视口高度的80%,可根据需求调整数值。
  • 补充宽度是为了避免窗口撑满屏幕,提升视觉体验,可按需修改。
  • 子元素内的display:flex布局属于可选优化,目的是让内部元素排版更美观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:45:55