Responsive Video Resizing - Matt Smith

There are a number of options for implementing responsive images, e.g., the <picture> element, client-side polyfills, automatic cropping, et al. But what about video?

Many of the examples I see in responsive layouts replace video with a static image in smaller viewports. That may be because of concerns regarding data use across mobile networks. But let’s say for the moment we wanted to make video fully responsive on the web.

We’ll start here:

<video> <source src="my_video.webm" type="video/webm"> <source src="my_video.mp4" type="video/mp4"> </video>

To produce an effect that maintains the video’s aspect ratio when the parent container changes, similar to background-size: contain, the height and width needs to be set to 100%:

video { height: 100%; width: 100%; }

That’s the bare minimum needed for responsive video.

See the Pen Responsive "background-size: contain" Video by Matt Smith (@AllThingsSmitty) on CodePen.

Now let’s try a solution similar to background-size: cover. This will still preserve the aspect ratio, however, if the video and its container have different dimensions then the video will be clipped on the left and right.

video { left: 50%; min-height: 100%; min-width: 100%; position: absolute; top: 50%; transform: translate(-50%, -50%); }

See the Pen Responsive "background-size: cover" Video by Matt Smith (@AllThingsSmitty) on CodePen.

Good idea?

Remember what I said before about data use? This could become expensive for users if you start serving video over mobile networks. Also, I’m not sure displaying video in smaller viewports is any more effective than well-cropped images. Nevertheless, it’s an interesting concept to consider. Happy coding.

  • CSS
  • mobile

Từ khóa » Html5 Video Scale To Fit Div