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

映射渲染React组件后如何实现等宽两列布局,现有grid等设置失效怎么办

两列等宽布局实现方案

问题原因

  • 承载列表的父容器RecentTemplatesList未设置明确的多列布局规则,之前配置的grid相关属性未生效大概率是没有正确写在父容器样式中
  • 子组件ListRecentTemplates写死了固定宽度200px,无法适配父容器的列宽分配规则

修复代码

1. 修改父容器RecentTemplatesList样式

const RecentTemplatesList = styled.div`
  position: relative;
  overflow: auto;
  height: 25vh;
  padding: 20px 16px;
  /* 新增以下grid配置实现等宽两列 */
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px; /* 两列之间、上下行之间的间距,可自行调整数值 */
`

2. 修改子组件外层容器ListRecentTemplates样式

const ListRecentTemplates = styled.div`
  padding: 10px 12px;
  flex-direction: column;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: space-between;
  border-radius: 5px;
  width: 100%; /* 把固定宽度200px改成100%,适配父容器分配的列宽 */
  background-color: #e5f7f4; // color from template
`

补充说明

如果需要优先保证列高度自适应,不想要上下间距可以把gap的上下值设为0,只保留左右间距,写法改成gap: 0 16px;即可。如果要兼容老版本浏览器,也可以用flex实现:父容器设置display: flex; flex-wrap: wrap; justify-content: space-between;,然后子组件设置width: calc(50% - 8px);,效果和grid方案一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:54:03