DEV Community

Cover image for Center Video HTML - [SOLVED]
ProgrammerMoney
ProgrammerMoney

Posted on • Updated on

Center Video HTML - [SOLVED]

TL;DR Summary

If you want to center a video in HTML then the simplest thing you can do is calculate the exact margins to position it in the center.

If you wanted to center the video horizontally then you just use margin-left property.

If you set margin to be 50% of the full screen width then the left edge of the video will be exactly in the center of the screen.

What you want is to push it back left for half of a width of the video (in our case 200px) and that will make it perfectly centered.

The same goes for vertical center alignment.

<style>
  body { background-color: salmon; }
  video {
    width: 400px; /* height is 225px */
    margin-left: calc(50vw - 200px); 
    margin-top: calc(50vh - 112px);
  }
</style>

<video controls>
  <source src="test_video.mp4" type="video/mp4">
</video>
Enter fullscreen mode Exit fullscreen mode

And the result looks like this:

center video html

In short that is it.

More Details

To center video element in HTML we used values like vw and vh. Those are viewport width and viewport height respectively.

Basically what it means is that 100vw is the full screen width and 100vh is the full screen height.

So 50vw is exactly horizontal center of the screen and 50vh is exactly vertical center of the screen.

Also remember that sometimes you won't have full screen available and the video element will be inside some other smaller element. In that case you might want to use 50% instead of 50vw.

Something like this:

margin-left: calc(50% - 200px);
Enter fullscreen mode Exit fullscreen mode

And this is really all there is to centering video in HTML using simple margin-left and margin-top CSS properties.

Until next time,

Will

Senior Developer & SEO Algo Specialist

Also creator of:

Top comments (0)