You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tailwind实现视频播放器播放按钮的垂直水平居中?

解决Tailwind视频播放器播放按钮居中问题

你的代码中按钮和视频是flex容器的同级子元素,会横向排列,无法实现按钮覆盖在视频上方居中的效果。以下是修正后的实现方案:

修改后的代码

<div style="width: 600px; height: 300px;" class="relative">
    <video id="vid1" width="600" height="300" controls style="width: 100%; height: 100%;" class="video-js vjs-default-skin" preload="auto">
        <source :src="url" type="video/mp4">
    </video>
    <button class="absolute inset-0 m-auto w-20 h-20 rounded-full bg-blue-500 hover:bg-red-500 text-white flex items-center justify-center">
        <i class="el-icon-video-play text-2xl"></i>
    </button>
</div>

关键改动说明

  • 将容器的flex items-center justify-center替换为relative,使其成为绝对定位元素的参考容器
  • 调整按钮和视频的顺序,让按钮位于视频之后(默认层级更高,可直接覆盖在视频上方)
  • 给按钮添加absolute inset-0 m-auto组合类:
    • absolute:开启绝对定位
    • inset-0:让按钮的上下左右边界贴紧父容器
    • m-auto:通过自动边距实现水平垂直居中
  • 缩小按钮尺寸(原w-72 h-72会超出视频容器,改为w-20 h-20,可按需调整)
  • 给按钮添加flex items-center justify-center,确保内部播放图标也居中

可选交互优化(点击按钮播放视频)

如果需要点击按钮后自动播放视频并隐藏按钮,可添加以下JS逻辑:

const playBtn = document.querySelector('button');
const video = document.getElementById('vid1');

playBtn.addEventListener('click', () => {
    video.play();
    playBtn.classList.add('hidden');
});

video.addEventListener('pause', () => {
    playBtn.classList.remove('hidden');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:48:23