Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Video: Retain aspect ratio when resizing

Tags:

html

css

video

I have a video element set to 100% width in a container div. That div has a max-width of 800px and min-width of 400px. When resizing the browser I need the video element to resize while retaining its original aspect ratio. Currently it resizes in width but remains its original height, adding letterbox bars above and below to make up for it.

Is it possible to resize the video element dynamically like this without resorting to Javascript?

like image 701
Brandon Durham Avatar asked Oct 21 '10 17:10

Brandon Durham


People also ask

How do I lock aspect ratio in HTML?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do you preserve aspect ratio when scaling images?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.

How do I change the aspect ratio on a video tag?

HTML Video Tags All you need to do is set the width to 100% and the height to auto. This will create a video that fills the entire parent and its height will be calculated automatically based on the width so that it maintains its current aspect ratio no matter the screen size.

How do you make a video full width in CSS?

Try using max-width and max-height instead. By setting the width and height to 100%, you might be stretching the video to fit those exact dimensions.


1 Answers

According to the box model, in the section on replaced elements, this should work as you expect: Since the video has a height of auto and a set width, and it has an intrinstic ratio (as videos do), then the used value of height should be computed based on those. Make sure you are not specifying the height anywhere — the following CSS worked for me:

video {
    width: 100%;
}
div {
    max-width: 800px;
    min-width: 400px;
}

Try explicitly adding height: auto to the video — maybe with !important to see if it’s getting set somewhere else.

like image 176
Josh Lee Avatar answered Oct 02 '22 17:10

Josh Lee