Have you ever wished you could use background-size:cover; on regular elements? Well, it turns out you can with a CSS property called object-fit
- and with the recent release of FireFox 36, we can start to use it in our designs as we have really good browser support for it.
https://codepen.io/wesbos/pen/YPmyxy
It's a popular design trend to have videos and images span the entire width and height of an element. Problems arise when it comes to the media's ratio - they never quite fit perfectly width and height wise - especially with dynamic content and responsive viewports.
Enter object-fit. It's a new CSS3 property that we can use to stretch embedded media (videos and images) across the entire parent, while still maintaining the aspect ratio. No JavaScript required!
How does it work? It's pretty easy - first you start with a container that has a defined width and a height on it - for our purposes I'm using viewport units so get a perfect 100% width and height of the screen. Then on the video or image itself, we use object-fit: cover;
. You'll now see the video span across the entire element - it's cropped either at the left/right or the top/bottom to ensure full coverage.
We can also use object-fit:contain;
, which is the same as background-size:cover;
, it won't crop the video but rather show ensure the entire video is always visible. There are a few more values available, but these are the most likely use cases when trying to replicate background-size:cover;
with a video.
Check out the demo - https://codepen.io/wesbos/full/YPmyxy/ or view the code below. Enjoy!
Find an issue with this post? Think you could clarify, update or add something?
All my posts are available to edit on Github. Any fix, little or small, is appreciated!