如何强制Video元素遵守父容器的max-height限制?
解决视频超出父容器max-height限制的问题
问题重现
原代码如下:
<style> .gl { width: 50%; } .pl { width: 100%; max-height: 50vh; background: red; } video { display: block; height: 100%; margin: 0 auto; } </style> <div class='gl'> <div class='pl'> <video src='/1111.mp4'></video> </div> </div>
问题表现:视频忽略父容器max-height: 50vh的限制,高度超出红色父容器范围,无法适配不同宽高比的视频。
解决方案
修改视频的样式,通过max-height和max-width结合保持宽高比,同时限制视频在父容器范围内:
<style> .gl { width: 50%; } .pl { width: 100%; max-height: 50vh; background: red; overflow: hidden; /* 可选,防止极端情况溢出 */ } video { display: block; max-height: 100%; /* 视频最大高度不超过父容器高度 */ max-width: 100%; /* 视频最大宽度不超过父容器宽度 */ width: auto; /* 自动计算宽度,保持宽高比 */ height: auto; /* 自动计算高度,保持宽高比 */ margin: 0 auto; /* 水平居中 */ } </style> <div class='gl'> <div class='pl'> <video src='/1111.mp4'></video> </div> </div>
原理说明
- 去掉原
height: 100%的强制设置,改用max-height:100%和max-width:100%,让视频根据自身宽高比自动缩放,同时不超出父容器的尺寸限制。 width: auto和height: auto确保视频始终保持原始宽高比,不会被拉伸变形。- 父容器添加
overflow: hidden是可选的,用于避免视频因浏览器渲染精度问题出现细微溢出。
内容的提问来源于stack exchange,提问作者flex
相关产品推荐
相关产品推荐

