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

修改flex-direction为row时div消失的CSS布局问题求助

问题解决:Flex布局改row后子元素消失,实现两侧排列

问题原因

把#row7的flex-direction从column改为row后,#first和#second作为flex容器的子元素,默认没有设置宽度/弹性占比;再加上它们内部的.green、.red使用百分比宽度(依赖父元素宽度),父元素宽度为0的情况下,这些色块的宽度也会变成0,最终导致两个子div看起来“消失”了。

解决方案

修改CSS,给子元素分配空间,并调整内部布局:

#assignments-wrapper {
  padding: 1.5rem;
}

.assignment {
  min-height: 40px;
  margin-bottom: .5rem;
  background: black;
  display: flex;
}

.red {
  width: 5%;
  height: 40px;
  background: #DC3220;
}

.green {
  width: 5%;
  height: 40px;
  background: #1AFF1A;
}

.blue {
  width: 5%;
  height: 40px;
  background: #1A85FF;
}

#row7 {
  display: flex;
  flex-direction: row; /* 改为row */
  justify-content: space-between; /* 保持两侧分布 */
  gap: 1rem; /* 可选:给两个子元素加间距 */
}

/* 给两个子元素分配空间,让它们能显示内部色块 */
#first, #second {
  flex: 1;
  display: flex; /* 让内部色块水平排列 */
  gap: .2rem; /* 可选:色块之间加间距 */
  align-items: center; /* 可选:垂直居中色块 */
}

#first .red {
  height: 10px;
  width: 10%; /* 现在父元素有宽度,百分比生效 */
}

#first .green {
  height: 15px;
  width: 10%;
}

#second .red {
  height: 10px;
  width: 10%;
}

#second .green {
  height: 15px;
  width: 10%;
}

效果说明

  • flex: 1让#first和#second平分父容器的水平空间(如果需要不同占比可以调整数值,比如flex: 2和flex: 1);
  • display: flex给两个子元素内部加上flex布局,让里面的色块水平排列,匹配你想要的效果;
  • justify-content: space-between确保两个子元素分别靠向父容器的左右两侧。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:35:31