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

使用swiper-master对齐含图片的li元素 不熟悉display:flex如何实现布局

解决Swiper带图片slide对齐问题的方案

你现有代码的核心问题是.swiper-slide设置了固定100vh高度,且默认垂直居中对齐内容,导致带图片的slide无法实现预期排布,按以下步骤修改即可:

  • 调整Swiper JS配置
    如果需要实现两行多列的排布效果,新增grid配置项即可:
var swiper = new Swiper('.swiper-container', {
    direction: 'horizontal',
    slidesPerView: 4,
    spaceBetween: 4, 
    freeMode: true,
    mousewheel: true, 
    // 新增两行排布配置
    grid: {
      rows: 2,
      fill: 'row'
    }
});
  • 修改.swiper-slide CSS属性
    把垂直对齐方式改为顶部对齐,同时去掉固定高度设置,让高度自适应内容:
.swiper-slide {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    /* 垂直对齐改为顶部 */
    -webkit-box-align: start;
    -ms-flex-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
    flex-shrink: 0;
    width: 100%;
    /* 去掉固定100vh,改为自适应内容高度 */
    height: auto;
    position: relative;
    background: #fff;
    text-align: center;
    font-size: 18px;
    transition-property: transform
}
  • 新增图片适配样式
    避免slide内的图片变形或溢出:
.swiper-slide img {
    width: 100%;
    height: auto;
    display: block;
    /* 如果需要所有图片统一高度,可自行添加固定高度配置,例:height: 180px; */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:00:01