Let's say I have a very simple HTML page with a single HTML5 video element. It's source code is:
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<video height="{HEIGHT}" width="{WIDTH}" controls="">
<source src="{SOURCE}" type="{TYPE}"/>
</video>
</body>
</html>
What can I do to center that video element both horizontally and vertically in the web browser? I'd prefer a CSS solution or at least a solution that uses as little in the way of hackish techniques as possible, but I'll take what I can get.
Use following css will make your video element center vertically and horizontally.
video {
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
}
Working Fiddle
Couple of ways to achieve it (Added jQuery to help others as well):
Method 1: Add this class in your video
CSS:
.center {
position: absolute;
//Option 1
top:50%; left: 50%;
margin-left: -150px;
margin-top: -75px;
//Option 2 (Needs to check browser compatibility)
top: calc(50%-75px);
left: calc(50%-150px);
}
Method 2: Add some code for dynamic margins
CSS:
.center {
position: absolute;
top: 50%;
left: 50%;
}
Code:
$('video').css({
'margin-top': - $('video').height()/2,
'margin-left': - $('video').width()/2
});
Method 3: Window size
Code:
$(window).on('load resize', function(){
$('video').css({
'position' : 'absolute',
'top': $(window).height()/2 - $('video').height()/2,
'left': $(window).width()/2 - $('video').width()/2
});
});
Here is a link How to center an element horizontally and vertically for more detailed description.
For background video i use this
HTML:
<video class="background" controls="">
<source src="{SOURCE}" type="{TYPE}"/>
</video>
CSS:
.background {
position: fixed;
right: 0px;
bottom: 0px;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With