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:
- It requires a wrapper element, so copying and pasting code directly from YouTube is not possible. Users need to be smarter.
- If you have old content and are redesigning to fluid, all old videos need HTML tweaks.
- 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):
- 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
