My goal is to have a video that takes up the full width of the screen, but if the video would be too tall and take up more than the entire viewport (would need to scroll to see the whole video), it will shrink to fit the container (with borders added on the left and right to fit the screen).
I assumed this would be pretty simple with just HTML and CSS. This was my original idea, but the video overflows below the containing div instead of shrinking to fit inside of the div:
HTML (video is just a placeholder):
<div class="video-row">
<video class="video">
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
</div>
CSS (I added the borders to be able to see the video overflowing):
* {
padding: 0;
margin: 0;
}
.video-row {
border: 3px red dotted;
width: 100%;
max-height: 100vh;
}
.video {
border: 3px blue solid;
width: 100%;
height: 100%;
object-fit: contain;
}
Here is a JFiddle with this code: https://jsfiddle.net/2L8qayfn/
In my mind, the video’s object-fit: contain;
should make the video shrink to fit in the container, but its overflowing below the div, as you can see with the borders. The div seems to be the right size, but the video keeps overflowing and I’m not sure why. I think the problem might be with max-height cropping instead of resizing but I don’t know how I would set the max height of the div with the max-height property.
I’ve tried a wide variety of other methods, but this seems to be the closest to making it behave how I want. If needed, I can hardcode the resolution of the video (1920×1080) but would prefer to keep it generalized. I am also able to use Javascript, but would prefer to keep it pure HTML/CSS if possible.
Jared Swislow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.