You need to enable JavaScript to run this app. 如何在非全屏容器中让Vimeo iframe实现background-size: cover效果
优惠活动
大模型
产品
解决方案
定价
更多

如何在非全屏容器中让Vimeo iframe实现background-size: cover效果

适配非全屏容器的Vimeo背景视频实现方案

你无需修改现有HTML结构,直接替换对应CSS代码即可实现background-size: cover的效果,完整修改后的代码如下:

CSS代码(现代浏览器兼容方案,Chrome 105+、Safari 16+、Firefox 110+支持)

.video-background {
  position: relative;
  overflow: hidden;
  /* 按你的需求设置容器尺寸:固定高度400px,宽度自适应 */
  width: 100%;
  height: 400px;
  /* 开启容器查询,后续比例判断将基于当前容器而非整个视口 */
  container-type: size;
}

.video-background iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* 尺寸计算基准改为父容器而非浏览器视口 */
  width: 100cqw;
  height: 100cqh;
}

/* 容器宽高比大于16:9时,按宽度适配视频高度 */
@container (min-aspect-ratio: 16/9) {
  .video-background iframe {
    height: 56.25cqw;
  }
}

/* 容器宽高比小于16:9时,按高度适配视频宽度 */
@container (max-aspect-ratio: 16/9) {
  .video-background iframe {
    width: 177.78cqh;
  }
}

全浏览器兼容方案(兼容旧版本浏览器)

如果需要兼容不支持容器查询的旧版本浏览器,可以搭配以下JS代码实现,CSS只需保留基础定位和溢出隐藏逻辑即可:

CSS部分

.video-background {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 400px;
}

.video-background iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: none;
}

JS部分

// 计算并调整iframe尺寸
const adjustVimeoVideoSize = () => {
  const container = document.querySelector('.video-background')
  const videoIframe = container.querySelector('iframe')
  // 标准16:9视频比例,如果你用的视频比例不同可以自行修改
  const VIDEO_ASPECT_RATIO = 16 / 9
  const containerRatio = container.clientWidth / container.clientHeight

  if (containerRatio > VIDEO_ASPECT_RATIO) {
    videoIframe.style.width = `${container.clientWidth}px`
    videoIframe.style.height = `${container.clientWidth / VIDEO_ASPECT_RATIO}px`
  } else {
    videoIframe.style.height = `${container.clientHeight}px`
    videoIframe.style.width = `${container.clientHeight * VIDEO_ASPECT_RATIO}px`
  }
}

// 页面加载和窗口尺寸变化时触发调整
window.addEventListener('load', adjustVimeoVideoSize)
window.addEventListener('resize', adjustVimeoVideoSize)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 04:45:04