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

如何在Ant Design中实现首元素占两行的网格布局?

在Ant Design中实现指定网格布局的方案

要实现你用CSS Grid完成的那种布局(左侧元素占两行高度,右侧上下两个元素),可以通过Ant Design的Row和Col组件配合少量样式实现,同时解决间距和高度对齐问题,具体如下:

核心思路

  1. 利用Ant Design栅格的24列系统,将左侧元素分配12列(对应CSS Grid的1fr),右侧分配12列;
  2. 通过Row的gutter属性设置均等的水平/垂直间距,替代CSS Grid的gap;
  3. 让左侧元素的高度自动匹配右侧两个元素的总高度(含间距),实现对齐。

完整实现代码

import { Row, Col } from 'antd';
import './GridLayout.css'; // 自定义样式文件

const GridLayout = () => {
  return (
    <Row gutter={[5, 5]} className="grid-container">
      {/* 左侧元素:占12列,高度自动拉伸 */}
      <Col span={12} className="grid-item div1">
        <img src={require('../../../../assets/images/img1.jpg')} alt='' />
      </Col>
      {/* 右侧容器:占12列,内部垂直排列两个元素 */}
      <Col span={12}>
        <Row gutter={[0, 5]}>
          <Col span={24} className="grid-item div2">
            <img src={require('../../../../assets/images/img1.jpg')} alt='' />
          </Col>
        </Row>
        <Row>
          <Col span={24} className="grid-item div3">
            <img src={require('../../../../assets/images/img1.jpg')} alt='' />
          </Col>
        </Row>
      </Col>
    </Row>
  );
};

export default GridLayout;

对应的自定义样式GridLayout.css:

.grid-container {
  width: 100%;
  min-height: 400px; /* 可根据需求设置容器高度 */
}

.grid-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

.div1 {
  background-color: red;
  height: 100%; /* 让左侧元素高度占满父容器 */
}

.div2 {
  background-color: blue;
}

.div3 {
  background-color: green;
}

.grid-item img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保证图片自适应容器 */
}

关键细节说明

  • 间距设置:外层Row的gutter={[5,5]}设置水平和垂直间距为5px,右侧内部的Row设置gutter={[0,5]}保证两个垂直元素间的间距和外层一致;
  • 高度对齐:给左侧Col添加height: 100%,让它的高度自动匹配外层Row的高度,而右侧两个元素的总高度(含间距)会和左侧保持一致;
  • 图片自适应:通过object-fit: cover保证图片在容器内正确显示,不会变形。

替代方案(纯栅格嵌套)

如果不想额外写CSS,也可以通过嵌套Row的align属性实现高度拉伸:

<Row gutter={[5,5]} align="stretch" style={{ minHeight: 400 }}>
  <Col span={12} style={{ backgroundColor: 'red' }}>
    <img src={require('../../../../assets/images/img1.jpg')} alt='' style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
  </Col>
  <Col span={12}>
    <Row style={{ height: '100%', flexDirection: 'column' }}>
      <Col span={24} style={{ backgroundColor: 'blue', flex: 1, marginBottom: 5 }}>
        <img src={require('../../../../assets/images/img1.jpg')} alt='' style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      </Col>
      <Col span={24} style={{ backgroundColor: 'green', flex: 1 }}>
        <img src={require('../../../../assets/images/img1.jpg')} alt='' style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
      </Col>
    </Row>
  </Col>
</Row>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:55:29