search

Fluid Width Video

Apr 09, 2025 am 09:13 AM

Fluid Width Video

In today’s era of responsive and fluid web layouts, there is a type of media that hinders perfect harmony: video. There are many ways to display videos on the website. You may host your videos and go through HTML5<video></video> Tag display; may also be provided using YouTube, Vimeo or other<iframe></iframe> Code to display the video provider. Let's see how to keep all videos in fluid width while maintaining the proper aspect ratio.

In these video embedding scenarios, it is very common to declare static widths and heights.

<video ...="" controls="" height="300" width="400"></video>
<iframe ...="" height="300" width="400"></iframe>
<object ...="" height="300" width="400"></object>
<embed ...="" height="300" width="400"></embed>

Guess it? Declaring a static width in a fluid width environment is not a good idea. What happens if the video's parent container shrinks to less than the declared 400 pixels? It will overflow and may look ridiculous and awkward.

So can't we just do this?

<video ...="" width="100%"></video>

Yes, you can! If you are using standard HTML5 video, this will adapt the video to the width of the container. Importantly, when you do, remove the height declaration so that the video grows and shrinks to maintain its aspect ratio so that it does not have an awkward "bar" that fills the blank space (unlike an image, the actual video maintains its aspect ratio regardless of the size of the element).

You can do this via CSS (without worrying about what is declared in HTML):

 video {
  /* Override other styles for responsiveness*/
  width: 100% !important;
  height: auto !important;
}

<iframe></iframe> Videos (YouTube, Vimeo, etc.)

When the processing passes<iframe></iframe> Our above tips will not help when transmitting videos. Forced width of 100% is valid, but when we set height: auto we end up with a static height of 150 pixels, which is too short for most videos and causes more R&E (absurd and awkward).

Fortunately, here are a few possible solutions. One of them was first created by Thierry Kobletz and published on A List Apart in 2009: Creating Intrinsic Scale for Videos. Using this technique, you wrap the video in another element with an inherent aspect ratio and then absolutely position the video within that element. This allows us to obtain fluid width and reasonable heights that we can rely on.

<div class="videoWrapper">
  <iframe allowfullscreen="" frameborder="0" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" width="560"></iframe>
</div>
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  height: 0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

There is a clever adaptation method that allows you to adjust the aspect ratio directly from HTML, for example:

<div style="--aspect-ratio: 3 / 4;">
  <iframe ...></iframe>
</div>
.videoWrapper {
  ...
  /* Fallback to 16/9, otherwise use the ratio from HTML*/
  padding-bottom: calc(var(--aspect-ratio, .5625) * 100%);
}
 .videoWrapper iframe,
.videoWrapper embed,
.videoWrapper object { }

But...aspect ratio, old content, non-technical users, etc.

The above technique is great, but it has some possible limitations:

  1. It requires a wrapper element, so copying and pasting code directly from YouTube is not possible. Users need to be smarter.
  2. If you have old content and are redesigning to fluid, all old videos need HTML tweaks.
  3. All videos require the same aspect ratio. Otherwise, they will be cast to different aspect ratios and you will get "bars". Alternatively, you will need an applicable class name toolbox to adjust, which adds additional complexity.

If any of these restrictions apply to you, you may want to consider using a JavaScript solution.

Imagine: When the page loads, it will view all videos and save its aspect ratio. Perform immediately once, and whenever the window is resized, all videos are resized to fill in the available width and maintain their aspect ratio. Using the jQuery JavaScript library, it looks like this:

 // Find all YouTube videos // Extend this selector for Vimeo and any other content var $allVideos = $("iframe[src^='//www.youtube.com']"),

  // The element of fluid width $fluidEl = $("body");

// Calculate and save the aspect ratio of each video $allVideos.each(function() {

  $(this)
    .data('aspectRatio', this.height / this.width)

    // and remove the hard-coded width/height.removeAttr('height')
    .removeAttr('width');

});

// When the window is resized, $(window).resize(function() {

  var newWidth = $fluidEl.width();

  // Adjust the size of all videos according to the aspect ratio of each video $allVideos.each(function() {

    var $el = $(this);
    $el
      .width(newWidth)
      .height(newWidth * $el.data('aspectRatio'));

  });

// Start resize once to fix all videos when the page is loading}).resize();

This is where FitVids.js comes from

In addition to handling all this resizing work, FitVids.js loops through all videos and adds an HTML wrapper with aspect ratio enabled and the necessary CSS. This is much more efficient than needing to bind to a window resizing handler!

Use pure JavaScript instead

Nowadays, jQuery is no longer very popular. Fortunately, Dave has a Vanilla version (requires self-produced CSS):

  1. In fact, if not otherwise stated, all browsers render iframe, canvas, embed, and object tags as 300 pixels × 150 pixels. Even if this is not in the UA stylesheet.

The output maintains the original image and its format. The text has been paraphrased and reorganized for improved flow and readability while preserving the original meaning.

The above is the detailed content of Fluid Width Video. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
A Little Reminder That Pseudo Elements are Children, Kinda.A Little Reminder That Pseudo Elements are Children, Kinda.Apr 19, 2025 am 11:39 AM

Here's a container with some child elements:

Menus with 'Dynamic Hit Areas'Menus with 'Dynamic Hit Areas'Apr 19, 2025 am 11:37 AM

Flyout menus! The second you need to implement a menu that uses a hover event to display more menu items, you're in tricky territory. For one, they should

Improving Video Accessibility with WebVTTImproving Video Accessibility with WebVTTApr 19, 2025 am 11:27 AM

"The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect."- Tim Berners-Lee

Weekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteWeekly Platform News: CSS ::marker pseudo-element, pre-rendering web components, adding Webmention to your siteApr 19, 2025 am 11:25 AM

In this week's roundup: datepickers are giving keyboard users headaches, a new web component compiler that helps fight FOUC, we finally get our hands on styling list item markers, and four steps to getting webmentions on your site.

Making width and flexible items play nice togetherMaking width and flexible items play nice togetherApr 19, 2025 am 11:23 AM

The short answer: flex-shrink and flex-basis are probably what you’re lookin’ for.

Position Sticky and Table HeadersPosition Sticky and Table HeadersApr 19, 2025 am 11:21 AM

You can't position: sticky; a

Weekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryWeekly Platform News: HTML Inspection in Search Console, Global Scope of Scripts, Babel env Adds defaults QueryApr 19, 2025 am 11:18 AM

In this week's look around the world of web platform news, Google Search Console makes it easier to view crawled markup, we learn that custom properties

IndieWeb and WebmentionsIndieWeb and WebmentionsApr 19, 2025 am 11:16 AM

The IndieWeb is a thing! They've got a conference coming up and everything. The New Yorker is even writing about it:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor