video 默认不居中因其是行内级替换元素,需用 flex 布局(父设 min-height、子设 max-width/aspect-ratio)或 block+margin:auto 方案;避免使用 position+transform。
直接写 不加任何样式时,它表现得像 :宽度由内容决定、对齐方式遵循行内布局规则,上下有基线间隙。所以即使设了 width: 100%,也大概率不会水平居中——父容器没声明文本对齐,子元素就按左对齐走。
用 display: flex 是目前兼容性好、行为可预测的做法。关键点不是“只加 justify-content”,而是整套配合:
min-height: 100vh 或固定值),否则 align-items: center 没参照 自身建议设 max-width: 100% 和 height: auto,避免拉伸变形aspect-ratio: 16 / 9 配合 object-fit: cover 控制裁剪.video-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #000;
}
video {
max-width: 100%;
height: auto;
aspect-ratio: 16 / 9;
object-fit: cover;
}
很多人试过 margin: 0 auto 失败,是因为它只对「块级且宽度明确」的元素生效。对 必须先改显示类型:
display: block(否则仍是行内级,margin 无效)width(哪怕只是 width: 80%),不然 auto 水平方向无计算依据text-align: center,对 display: block 的 video 无效,别混用video {
display: block;
width: 80%;
margin: 0 auto;
}
像 position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%) 看似能居中,但隐患明显:
transform 对 渲染有闪烁或黑屏问题resize 事件重算除非你明确控制整个页面结构且兼容性要求极低,否则不推荐这条路。
真正难的不是让 video 居中,而是判断它是否该撑满容器、是否要保留原始宽高比、以及是否要适配全屏按钮触发后的重新居中逻辑——这些才是实际项目里容易漏掉的环节。