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?
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.
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.
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.
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.
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.
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