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

如何在Bootstrap的Row元素内居中卡片内容?

解决Bootstrap Row内卡片居中且间距不均的问题

问题代码:

<Row className="d-flex justify-content-center">
  {cardData.map((data) => {
    return (
      <Col>
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src={data.img} />
          <Card.Body>
            <Card.Title>{data.title}</Card.Title>
            <Card.Text>{data.text}</Card.Text>
            <Button variant="primary">{data.button}</Button>
          </Card.Body>
        </Card>
      </Col>
    );
  })}
</Row>

显示问题:卡片左右间距不均,无法在Row内正常居中。

解决方案1:给Col添加col-auto类

Bootstrap默认的Col会自动填充可用宽度,导致justify-content-center的居中逻辑失效。给Col添加col-auto类,让它仅包裹卡片内容,Row的居中样式就能正常生效:

<Row className="d-flex justify-content-center">
  {cardData.map((data) => {
    return (
      <Col className="col-auto">
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src={data.img} />
          <Card.Body>
            <Card.Title>{data.title}</Card.Title>
            <Card.Text>{data.text}</Card.Text>
            <Button variant="primary">{data.button}</Button>
          </Card.Body>
        </Card>
      </Col>
    );
  })}
</Row>

解决方案2:移除Col,直接在Row中放置卡片

如果不需要Col的响应式布局特性,可以直接将卡片放在Row内,通过给卡片添加横向margin来控制间距:

<Row className="d-flex justify-content-center">
  {cardData.map((data) => {
    return (
      <Card className="mx-2" style={{ width: "18rem" }}>
        <Card.Img variant="top" src={data.img} />
        <Card.Body>
          <Card.Title>{data.title}</Card.Title>
          <Card.Text>{data.text}</Card.Text>
          <Button variant="primary">{data.button}</Button>
        </Card.Body>
      </Card>
    );
  })}
</Row>

额外检查点

  • 确认Row的父容器没有设置固定宽度、overflow: hidden或其他限制居中的样式
  • 检查是否有自定义CSS覆盖了Bootstrap的默认类样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:50:15