如何使用 CSS 将视频居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17508729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:25:25  来源:igfitidea点击:

How do you center a video using CSS

cssvideocenter

提问by Rhiannon

I'm trying to center a video within my site but I don't want to use the center tags in HTML because it's kinda obsolete. How do I do this with CSS? Here's my HTML code if it's any help.

我试图在我的网站中居中视频,但我不想在 HTML 中使用中心标签,因为它有点过时了。我如何用 CSS 做到这一点?如果有帮助,这是我的 HTML 代码。

<center>
  <video width="320" height="240" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <source src="video.webm" type="video/webm">
    Your browser does not support the video tag.
  </video>
</center> 

回答by leoMestizo

Here's an example: http://jsfiddle.net/Cn7SU/

这是一个例子:http: //jsfiddle.net/Cn7SU/

Just add these CSS rules to the element video:

只需将这些 CSS 规则添加到元素video

display: block;
margin: 0 auto;

Add the display: blockproperty is very important. Otherwise you can't center the element.

添加display: block属性很重要。否则你不能将元素居中。

回答by Kerim

To center video horizontally add:

要水平居中视频添加:

display: block;
margin: 0 auto;

回答by Khaki

Here are 3 ways to center your video:

以下是将视频居中的 3 种方法:

1. Using margin

1. 使用保证金

video {
  display: block;
  margin: auto;
}

2. Using transform

2. 使用变换

video {
  margin-left: 50vw;
  transform: translate(-50%);
}

3. Using a container & flexbox

3. 使用容器和弹性盒

.container video {
  display: flex;
  justify-content: center;
}

回答by user760226

Try this, have a wrapper div around your video tag. html5 videos and images are treated like text when styling. So a text-align:center will work. You can check the fiddle below.

试试这个,在你的视频标签周围有一个包装 div。html5 视频和图像在样式化时被视为文本。所以 text-align:center 将起作用。您可以查看下面的小提琴。

<div class="video">  
  <video width="320" height="240" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <source src="video.webm" type="video/webm">
    Your browser does not support the video tag.
  </video>
</div>