如何在SVG容器内通过Flexbox将视频定位到左下角
问题解决:SVG容器内视频的定位与同步缩放(兼容Safari)
问题描述
现有一个按1.77宽高比实现垂直/水平居中的SVG容器,需要在其画布内左下角的固定矩形位置放置video元素,且视频需随浏览器窗口缩放与该矩形同步缩放。此前使用foreignObject方案在Safari中存在定位错误,现改用Flexbox实现。
解决方案
核心思路是通过相对定位的父容器作为视频的定位上下文,结合百分比尺寸与位置实现和SVG矩形的同步缩放,同时保持SVG的宽高比居中布局。
修改后的完整代码
CSS代码
* { margin: 0; padding: 0; overflow: hidden; } body { min-height: 100vh; display: flex; justify-content: center; align-items: center; font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } /* 包裹SVG和视频的容器,作为定位上下文 */ .svg-wrapper { position: relative; --aspectRatio: 1.7777777; width: min(100vw, 100vh * var(--aspectRatio)); height: min(100vh, 100vw / var(--aspectRatio)); } video { position: absolute; /* 基于SVG viewBox(1920x1080)计算百分比,匹配左下角矩形尺寸 */ width: calc(200 / 1920 * 100%); height: calc(300 / 1080 * 100%); /* 定位到SVG左下角,和矩形位置完全对齐 */ left: 0; bottom: 0; /* 确保视频填充容器,避免拉伸 */ object-fit: cover; } svg { width: 100%; height: 100%; }
HTML代码
<div class="svg-wrapper"> <video autoplay loop muted playsinline> <source src="https://ccp-odc.eva.mpg.de/matt/output-hevc-safari.mp4" type='video/mp4; codecs="hvc1"'> <source src="https://ccp-odc.eva.mpg.de/matt/output-vp9-chrome.webm" type="video/webm"> </video> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1920 1080" xml:space="preserve"> <rect fill="#00A99D" width="1920" height="1080" /> <rect y="780" fill="#208096" width="200" height="300" /> <rect x="860" y="390" fill="#208096" width="200" height="300" /> </svg> </div>
关键调整说明
- 新增定位容器:
.svg-wrapper采用相对定位,同时复用SVG的宽高比计算逻辑,确保容器尺寸和SVG完全一致,为视频提供准确的定位基准。 - 百分比尺寸计算:视频的宽高基于SVG的
viewBox(1920×1080)与目标矩形的尺寸(200×300)计算百分比,保证缩放时和矩形完全同步。 - 精准定位:
left: 0和bottom: 0直接将视频锚定到容器左下角,和SVG内的目标矩形位置完全对齐。 - 视频适配:添加
object-fit: cover确保视频填充容器,避免拉伸变形。 - 容器全屏适配:给
body设置min-height: 100vh,确保居中布局在所有视口下生效。
内容的提问来源于stack exchange,提问作者Kalaschnik
相关产品推荐
相关产品推荐

