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

如何用React+TailwindCSS实现响应式居中5卡片两行网格布局

React+TailwindCSS服务卡片布局实现:首行3个、末行2个居中及响应式适配

核心问题分析

你当前的问题在于:

  • 自定义CSS强制最后两个卡片跨列,导致尺寸不一致
  • 拆分两行会破坏响应式逻辑,无法适配不同屏幕尺寸

解决方案代码

1. 重构Card组件(统一卡片样式)

function Card({ service }) {
  return (
    <article className='bg-pink-400 p-6 rounded-lg flex flex-col items-center text-center w-full max-w-sm'>
      <img src={service.icon} alt={`${service.label} icon`} className='w-16 h-16 mb-4 object-contain' />
      <h4 className='text-lg font-semibold mb-2'>{service.label}</h4>
      <p className='text-gray-700 flex-grow'>{service.content}</p>
    </article>
  );
}

2. 修改ServicesComponent的布局容器

import React from 'react';
import { MainServicesArray } from '../../utils/data/CompanyData';

function ServicesComponent() {
  return (
    <section className='min-h-screen w-full py-8'>
      <div className='w-full'>
        <section className='py-4 px-10 text-center'>
          <h3 className='text-gray-600'>Our Services</h3>
          <span className='text-colour3 font-semibold block mt-1'>
            Our Professional and Independent Services
          </span>
          <div className='border-b-2 border-colour5 w-24 mx-auto mt-2'></div>
        </section>

        <section className='w-4/5 mx-auto mt-6'>
          <div className='service-grid grid gap-6'>
            {MainServicesArray.map((service) => (
              <Card service={service} key={service.label} />
            ))}
          </div>
        </section>
      </div>
    </section>
  );
}

3. 添加Tailwind兼容的自定义CSS

在全局CSS文件中添加:

@tailwind base;
@tailwind components;
@tailwind utilities;

/* 桌面端(≥1024px)布局:首行3个,末行2个居中 */
@media (min-width: 1024px) {
  .service-grid {
    grid-template-columns: repeat(3, minmax(270px, 1fr));
  }
  
  /* 当有5个元素时,调整最后两个的位置实现居中 */
  .service-grid > article:nth-last-child(2):nth-child(4) {
    grid-column-start: 2;
  }
  .service-grid > article:nth-last-child(1):nth-child(5) {
    grid-column-start: 3;
  }
}

/* 平板端(768px-1023px):2列布局 */
@media (min-width: 768px) and (max-width: 1023px) {
  .service-grid {
    grid-template-columns: repeat(2, minmax(270px, 1fr));
    justify-items: center;
  }
}

/* 手机端(≤767px):单列布局 */
@media (max-width: 767px) {
  .service-grid {
    grid-template-columns: 1fr;
    justify-items: center;
  }
}

关键逻辑说明

  1. 统一卡片尺寸:给卡片添加w-full max-w-sm和flex-grow,确保所有卡片宽度一致,内容高度自适应时不会变形。
  2. 响应式断点控制:
    • 桌面端(≥1024px):3列布局,通过nth-child选择器将第4、5个卡片定位到第2、3列,实现末行居中的倒三角形态。
    • 平板端(768px-1023px):2列布局,自动将5个元素分为2+2+1,最后一个卡片居中。
    • 手机端(≤767px):单列布局,卡片全屏宽度居中。
  3. 避免跨列变形:取消强制跨列的逻辑,保持每个卡片独立占一列,从根本上解决尺寸不一致问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:25:20