Skip to content

Latest commit

 

History

History
23 lines (16 loc) · 1.95 KB

CSS object-fit is background-size - cover for video.mdx

File metadata and controls

23 lines (16 loc) · 1.95 KB
title slug image category date id
CSS object-fit is background-size - cover; for video!
css-object-fit
ss-2015-04-13-at-4.03.32-PM.png
CSS
2015-04-13 09:05:04 -0700
3484

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.

http://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 <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit">available</a>, but these are the most likely use cases when trying to replicate background-size:cover; with a video.

Check out the demo - http://codepen.io/wesbos/full/YPmyxy/ or view the code below. Enjoy!