Table of Contents
But...aspect ratio, old content, non-technical users, etc.
This is where FitVids.js comes from
Use pure JavaScript instead
Home Web Front-end CSS Tutorial Fluid Width Video

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>
Copy after login

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>
Copy after login

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;
}
Copy after login

<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>
Copy after login
.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  height: 0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
Copy after login

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>
Copy after login
.videoWrapper {
  ...
  /* Fallback to 16/9, otherwise use the ratio from HTML*/
  padding-bottom: calc(var(--aspect-ratio, .5625) * 100%);
}
Copy after login
 .videoWrapper iframe,
.videoWrapper embed,
.videoWrapper object { }
Copy after login

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();
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Creating Your Own Bragdoc With Eleventy Creating Your Own Bragdoc With Eleventy Mar 18, 2025 am 11:23 AM

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

See all articles