Reputation: 6338
I've read a lot of SO posts on resizing video to fit the browser and/or parent element, but none of them do what I need. I have a single-page app with overflow: hidden
so the app doesn't scroll.
The app has various display:flex
containers, and in one of those I want to have a 16x9 video.
I want the whole video to always fit into its container (so there will be bars on top/bottom if the container is too wide, and bars on left/right if the container is too tall). I can use width: 100%
on the video to make it resize based on container width, but I can't figure out any way to make it shrink to fit when the container height gets smaller. (I'm guessing that's because most web pages grow vertically, so restricting based on height is less important.)
I've figured out that, at least on Chrome, the video
tag does not allow height
to be a percentage, and the W3C spec agrees with that, unfortunately. I've tried the trick with a relative-positioned video-wrapper with padding-bottom: 56.25%
and then putting the absolute-positioned video into that, but it still cuts off the bottom of the video when the container is too wide.
Here's a jsfiddle; it's easier to see there than to write about it: https://jsfiddle.net/darkstarsys/q1fr9jwd/2/
In there you'll see the video reacts correctly to its container's width, but the bottom of the video is cut off when the height is small. Play with the main
element's height and width to see how it reacts to its container size.
I'd like to avoid a Javascript-based solution if possible; seems like CSS ought to be able to do this somehow.
Upvotes: 6
Views: 4997
Reputation: 86
I'm not sure if this is what you want, but try it:
.main {
/*overflow: hidden;*/
/* TRY ASPECT RATIOS HERE
800w x 300h doesn't work -- bottom gets cut off */
width: 800px;
height: 300px;
background: red;
}
.video-wrapper {
display: flex;
height: 100%;
}
.video {
width: 100%;
height: auto; /* spec says no percent allowed here */
}
Upvotes: 7