Seamlessly adaptive HTML5 video playback

Has anyone figured out how to make an HTML5 video in an absolutely positioned <video> element resize to fit the window width and height without ever getting cropped? Many solutions I've come across rely on using the <iframe> tag, which is not an option for me, or only adjust based on width (something I can already do).

Essentially, I want the video to be as large as possible while also ensuring it doesn't get cut off if the window size changes - even in IE9. (Just to clarify: The video needs to keep its original aspect ratio, so black bars are acceptable.)

Here's what I've attempted so far.

/*CSS*/

#player-overlay {
  position: absolute;
  display: none;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000        
    z-index:999;
}
<!--HTML-->

<div id="player-overlay">
  <video width="100%" video="100%" style="width:100%, height:100%">
    <source src="../static/video/10s.mp4" />
    <source src="../static/video/10s.webm" type='video/webm; codecs="vp8, vorbis"' />
    <source src="../static/video/10s.ogv" type='video/ogg; codecs="theora, vorbis"' />
  </video>    
</div>

It looks like I might have to resort to writing a JavaScript solution instead.

Answer №1

Applying width and max-height to the <video> element will ensure proper display:

<div id="player-overlay">
    <video>
        <source src="../static/video/10s.mp4" />
        <source src="../static/video/10s.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/10s.ogv" type='video/ogg; codecs="theora, vorbis"' />
    </video>    
</div>
video {
    width: 100%;
    max-height: 100%;
}

Explore this link for more insights.

Additionally, remember to include a semicolon after background-color. In positioning elements to fill the screen, consider using top, bottom, left, and right properties rather than height and width.

Answer №2

(Although this discussion is from a while back, I'm optimistic that my response will be beneficial to someone in need.)

It seems like you already had the correct solution at hand. The style="width:100%, height:100%" on your <video> tag is effective, but remember to use a semicolon instead of a comma. It's unnecessary to include the redundant width="100%" and height="100%" attributes.

The reason why width: 100%; height: 100% works (with a semicolon) is because even though the <video> element expands, the video itself maintains its aspect ratio, resulting in letterboxing or pillarboxing within the <video> container: .

An advantage of using height: 100% is that the video gets letterboxed precisely in the center, whereas with max-height: 100%, the video aligns to the top of the container.

Additionally, ensure that your <video> tag has display: block set. Otherwise, it defaults to display: inline, leaving white space at the bottom due to font descenders: There is a 4px gap below canvas/video/audio elements in HTML5.

As noted by @gilly3, don't forget to add a semicolon after background-color: #000. And obviously, remove display: none. =)

Here's the complete solution:

/*CSS*/

#player-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: 999;
}

video {
  display: block;
  width: 100%;
  height: 100%;
}
<!--HTML-->

<div id="player-overlay">
  <video controls>
    <source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm">
    <source src="http://techslides.com/demos/sample-videos/small.ogv"  type="video/ogg">
    <source src="http://techslides.com/demos/sample-videos/small.mp4"  type="video/mp4">
    <source src="http://techslides.com/demos/sample-videos/small.3gp"  type="video/3gp">
  </video>
</div>

View the code snippet in "full page" mode and resize your browser window to observe the letterboxing effect.

By the way, the original sources for your videos weren't working anymore, so I utilized sample videos found here: .

I hope this information proves helpful.

Answer №3

For a great solution, apply this CSS code- By using height: auto;, your container will be properly covered.

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

Answer №4

While searching for information on responsive videos, I unexpectedly discovered this helpful answer. I used a similar approach to create my own responsive video element.

If you're looking to gain a better understanding of the concept, check out this link: Height equals width Pure CSS

Your code implementation could resemble the following:

#player-overlay {
  position: relative;

  &:before {
    content:'';
    display: block;
    padding-top: 50%;  // A 2:1 ratio is achieved with 50%. Check the provided link for more details on ratios.
  }
}

video {
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  width: 100%;
}

To adjust the ratio, simply modify the padding-top value in the before pseudo-element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

What is the process for adding a dot to the package.json file using the npm-pkg command?

I need help using the npm pkg set command to create a package.json file with the following structure: { ... "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-l ...

Can Comet be implemented without utilizing PrototypeJs?

Can Comet be implemented without utilizing PrototypeJs? ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Trouble initializing Google Maps in an Angular directive

I'm currently working on integrating the Google Maps API into an Angular website, but I'm encountering initialization issues. Within my HTML page, I'm utilizing bootstrap nav nav-tabs and switching between tabs using an Angular controller. ...

Strange occurrences within the realm of javascript animations

The slider works smoothly up until slide 20 and then it suddenly starts cycling through all the slides again before landing on the correct one. Any insights into why this is happening would be greatly appreciated. This issue is occurring with the wp-coda- ...

Reset the jQuery star-rating plugin

I came across a useful plugin for star ratings called JQuery Star Rating by Daniel Upshaw. My question is, how can I reset the stars in a form using this plugin? $("#btn-reset").on('click', function() { //resetting other inputs $('#st ...

Choosing HTML components using Selenium in the Whatsapp application

Apologies in advance for any language errors. I am currently working on a script using selenium and python to identify all messages with photos in a group. The structure of all message boxes is the same. Repository: # feel free to check out my code if you ...

The Bootstrap Jumbotron section stubbornly stays above the footer

I'm currently working on a Bootstrap 3 page and facing an issue where the yellow area does not seamlessly transition into the green footer. Instead, there is a white space between the end of the yellow area and the start of the footer. How can I resol ...

Certain javascript files have had illegal characters mistakenly added to them

There seems to be an issue with the js files or server on certain pages, as they are not loading in Firefox: with firefox: SyntaxError: illegal character 癡爠浥湵楤猠㵛≶敲瑩捡汭敮產崻 ⽅湴敲⁩搨猩映啌敮畳Ⱐ獥灡牡瑥 ...

The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token). This solution somewhat accomplishes that: app.factory('User', ['$resource','$window', function($resource,$window,l ...

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...

Tips for managing state updates in React Redux

Currently, I am utilizing a reducer to manage the state in Redux. The current structure of my state is as follows: { activeConversation: "Jim" conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] user: {id: 8, username: &quo ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

Converting a Class Component to a Functional Component: Step-by-Step Guide

Recently, I have been transitioning from working on class components to function components in React. However, I am facing some issues with my functional component code after converting it from a class component. In my functional component code, there is ...

I am experiencing difficulty with aligning my input boxes to the center in my React-Native

Just a heads up, this is my first time diving into the world of React Native, so bear with me as I try to figure things out. Please be kind if my question seems silly... Here's a snapshot of what I currently have: https://i.stack.imgur.com/VWGFm.png ...

Aligning a sprite at the center of a div background

My button has a unique design where it consists of a sprite set as the background image of a div. The sprite sheet is laid out horizontally, and I have also scaled down the source image to fit the div. .button { background: url(sprite.png); backgr ...

Execute a function with parameters when a button is clicked dynamically using PHP

I am trying to execute a parameterised function in PHP using AJAX. Below is the code snippet of my dynamic button where I need to pass $sub_id to the delet(sub_id) function for executing some SQL: echo "<td><input type='submit' name=&a ...