Explain Codes LogoExplain Codes Logo

Simulate background-size:cover on <video> or <img>

css
responsive-design
viewport-units
transforms
Alex KataevbyAlex Kataev·Mar 6, 2025
TLDR

To emulate the behavior of background-size:cover for <video> or <img> elements, use object-fit: cover; in CSS. This adjusts the media to match the size of the containing box with proportional scaling, trimming any excess.

.cover-style { object-fit: cover; /* The key to our cover simulation */ }
<video class="cover-style" width="100%" height="100%" autoplay loop> <source src="video.mp4" type="video/mp4"> </video> <img class="cover-style" src="image.jpg" width="100%" height="100%">

Apply the class .cover-style to your media for an instant background-size: cover simulation.

Vintage browser-friendly styling

If you're aiming to bring modern media feel into an older browser environment, you might find that object-fit: cover; leaves you hanging. But CSS is a friend in need, as with a dash of viewport units and transformations, and you can achieve the same result with a feel of CSS3 compatibility Tour De Force.

.video-container { position: relative; /* Setting stage for positioning */ overflow: hidden; /* Trim any adventurers off the edge */ } .responsive-video { /* Ensuring full, unkempt coverage */ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); min-width: 100%; min-height: 56.25vw; /* Maintain aspect ratio or the video goes on a diet */ }

Tailored solution for every situation

One size doesn't fit all. Project's unique demands calls for custom solutions. Set your eyes on these key elements:

  • Use the power of viewport units and transforms for dynamic appeal.
  • Leverage media queries to cater to specific devices or resolution.
  • Consider polyfills such as object-fit-images for those environments that don't play along.

Reign over responsive design and dynamic content

Ensuring the video or image fluidly adapts to its container, responsiveness is key. On window resize, the aspect ratio is retained avoiding distortion. Here's a CSS approach for a dynamic user experience:

/* Every video needs a home where it fits just right */ .responsive-video { width: 100%; height: 100%; } /* Responsive remodelling on demand */ @media screen and (max-width: /* decorator's breakpoint */) { .responsive-video { width: auto; height: auto; /* Call for custom adjustment in specifications */ } }

Every project has intricate demands. In case of creating a video cover effect, keep an eye out for:

  • Aspect ratio: Make sure the diet doesn't spell out anorexia; avoid stretching and distortion.
  • Cross-browser video sources: The more friends you have, the merrier it gets. Comply with all browsers.
  • Debug output: Logs on logs; because no one wants to navigate blindly.