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

中等及小屏幕下React卡片未横向溢出反而缩小的问题

问题描述

我在React项目中使用Tailwind CSS开发了4个ServiceCard组件,大屏及以上设备显示正常。期望在中等屏幕设备上一次显示2张卡片并实现横向溢出(overflow-x),但实际效果却是卡片宽度被压缩而非溢出。

期望效果:中等屏幕下显示2张完整卡片,超出部分可横向滚动查看
实际效果:中等屏幕下所有卡片被压缩在一行,没有溢出滚动

ServiceCard.jsx

import React from 'react';

export const ServiceCard = ({ imageUrl, heading, description }) => {
  return (
    <div className="flex flex-col 2xl:h-28 xl:h-24 2xl:w-[14.5em] xl:w-[12em] lg:w-[11em] md:w-[21em] bg-cyan p-2 rounded-lg">
      <div className="flex flex-row items-center px-2">
        <img src={imageUrl} alt={heading} className="lg:w-8 xl:w-10"/> {/* Use the imageUrl prop */}
        <div className="2xl:ml-4 ml-2 font-bold 2xl:text-[15px] xl:text-[11px] lg:text-[11px]">{heading}</div> {/* Use the heading prop */}
      </div>
      <div className="mt-2 2xl:text-[10.5px] xl:text-[8px] lg:text-[7px] px-2">
        {description} {/* Use the description prop */}
      </div>
    </div>
  );
};

ServicesProvided.jsx

import React from 'react';
import { ServiceCard } from './ServiceCard';

export const ServicesProvided = () => {
  return (
    <div className="flex flex-row gap-x-6 ml-14 overflow-auto">
      <ServiceCard
        imageUrl="./doctor.png"
        heading="Top Rated Doctors"
        description="Find and book appointment with best medical professional in town"
      />
      <ServiceCard
        imageUrl="./doctor.png"
        heading="Top Rated Doctors"
        description="Find and book appointment with best medical professional in town"
      />
      <ServiceCard
        imageUrl="./doctor.png"
        heading="Top Rated Doctors"
        description="Find and book appointment with best medical professional in town"
      />
      <ServiceCard
        imageUrl="./doctor.png"
        heading="Top Rated Doctors"
        description="Find and book appointment with best medical professional in town"
      />
    </div>
  );
};
解决方案

问题核心是flex容器默认会让子元素自动收缩,导致卡片被压缩无法溢出滚动,按以下步骤修改:

  1. 给ServiceCard的根容器添加flex-shrink-0类,禁止卡片被压缩:
// 修改后的ServiceCard根元素
<div className="flex flex-col flex-shrink-0 2xl:h-28 xl:h-24 2xl:w-[14.5em] xl:w-[12em] lg:w-[11em] md:w-[21em] bg-cyan p-2 rounded-lg">
  1. 调整ServicesProvided的容器样式,明确指定横向溢出滚动:
// 修改后的ServicesProvided容器
<div className="flex flex-row gap-x-6 ml-14 overflow-x-auto pb-2">
  • overflow-x-auto:仅在内容超出时显示横向滚动条
  • pb-2:避免滚动条遮挡卡片底部(可选,根据实际布局调整)
  1. 可选优化:若要精准控制中等屏幕下仅显示2张卡片的可视区域,可在外层添加容器限制宽度:
// 外层包裹容器
<div className="md:max-w-[calc(2*21em+1.5rem)] overflow-hidden">
  <div className="flex flex-row gap-x-6 ml-14 overflow-x-auto pb-2">
    {/* ServiceCard组件 */}
  </div>
</div>

这里2*21em是两张md尺寸卡片的宽度总和,1.5rem对应gap-x-6的间距,确保可视区域刚好容纳2张卡片,超出部分可滚动查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:50:16