Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center an HTML5 video horizontally and vertically in a bare bones HTML document? [duplicate]

Tags:

html

css

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.

like image 634
Melab Avatar asked Jan 06 '16 05:01

Melab


3 Answers

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

like image 64
ketan Avatar answered Nov 15 '22 21:11

ketan


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.

like image 45
Kunj Avatar answered Nov 15 '22 21:11

Kunj


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;
   } 
like image 33
Lukáš Irsák Avatar answered Nov 15 '22 20:11

Lukáš Irsák