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

Swiper设置flex-col方向时宽度无限增大问题咨询

Swiper组件flex-col布局下宽度异常膨胀问题解决

问题描述

使用Swiper React组件时,父容器设置flex-col布局后,Swiper组件宽度会异常增大至约33599999999px,切换为flex-row布局则显示正常。

测试代码:

"use client"
import { Swiper,SwiperSlide} from 'swiper/react';
import {Pagination,Navigation} from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';

const Testing = () => {
    let arrayOfMonths = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','November','Décembre']
    let currentYear = (new Date()).getFullYear();

    const swiperSlides = () => ( arrayOfMonths.map((month,index) => (
        <SwiperSlide key={index} >
            <div className='text-center'>month</div>
        </SwiperSlide>
    )))

    const renderSwiper = () => {
        return (
            <Swiper 
            modules={[Navigation]}
            navigation
            spaceBetween={25}
            slidesPerView={1}
            >
                {swiperSlides()}
            </Swiper>
        )
    }


    return ( 
        <div className='flex flex-col gap-5 mt-5 mx-5 border bg-black md:flex-row'>
            {renderSwiper()}
            {renderSwiper()}
        </div>
     );
}
 
export default Testing;

正常显示(flex-row):
正常显示(flex-row)

异常显示(flex-col):
异常显示(flex-col)

原因分析

flex-col布局下,默认的items-stretch规则会让Swiper组件尝试填充父容器的可用宽度,而Swiper内部的水平滑动布局逻辑在这种场景下出现计算错误,导致宽度异常膨胀。flex-row布局时,Swiper的宽度被自然约束在父容器的水平空间内,因此不会触发该问题。

解决方案

方案1:给Swiper添加宽度约束

直接给Swiper组件添加w-full类(Tailwind),强制其宽度匹配父容器的可用宽度:

<Swiper 
    modules={[Navigation]}
    navigation
    spaceBetween={25}
    slidesPerView={1}
    className="w-full"
>
    {swiperSlides()}
</Swiper>

方案2:修改父容器的对齐方式

在父容器中添加items-start类,阻止子项自动拉伸宽度:

<div className='flex flex-col gap-5 mt-5 mx-5 border bg-black md:flex-row items-start'>
    {renderSwiper()}
    {renderSwiper()}
</div>

方案3:显式设置Swiper宽度

通过内联样式给Swiper设置宽度约束:

<Swiper 
    modules={[Navigation]}
    navigation
    spaceBetween={25}
    slidesPerView={1}
    style={{ width: '100%', maxWidth: '100%' }}
>
    {swiperSlides()}
</Swiper>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:22:07