如何实现全屏宽度视频:视口过高时自动收缩适配容器
解决方案
纯CSS通用方案(无需硬编码视频分辨率)
修改你的CSS代码如下:
* { padding: 0; margin: 0; } .video-row { border: 3px red dotted; width: 100%; max-height: 100vh; /* 用flex布局让视频在容器内自动适配并居中 */ display: flex; justify-content: center; align-items: center; overflow: hidden; } .video { border: 3px blue solid; /* 先让视频占满容器宽度 */ width: 100%; /* 限制视频最大高度不超过容器 */ max-height: 100%; /* 保持视频比例,自动收缩适配容器 */ object-fit: contain; }
原代码失效原因
你给.video设置了height: 100%,但父元素.video-row仅定义了max-height:100vh,没有明确的height值,导致height:100%没有有效参考高度,视频会按照自身原始尺寸渲染,最终超出容器范围。
通过给父元素添加flex布局,容器会根据子元素的实际尺寸调整自身高度(但不超过max-height:100vh),再配合视频的max-height:100%和object-fit:contain,就能让视频在保持比例的前提下,自动收缩适配容器的高度限制,同时占满容器宽度。
已知视频分辨率时的优化方案(可选)
如果明确知道视频宽高比(比如1920x1080对应的16:9),可以用aspect-ratio属性优化,让容器始终保持视频比例,避免不必要的空白:
.video-row { border: 3px red dotted; width: 100%; max-height: 100vh; aspect-ratio: 16/9; margin: 0 auto; display: flex; justify-content: center; align-items: center; overflow: hidden; } .video { border: 3px blue solid; width: 100%; height: 100%; object-fit: contain; }
这种方式会让容器固定为16:9比例,同时最大高度不超过视口,视频会完全适配容器,容器的红色虚线边框会自动填充屏幕左右剩余空间。
内容的提问来源于stack exchange,提问作者Jared Swislow
相关产品推荐
相关产品推荐

