Incorporating a YouTube or Vimeo video while maintaining the proper aspect ratio

On my video page, I embed Vimeo videos dynamically with only the video ID. This causes issues with the aspect ratio as black bars appear on the sides due to the lack of width and height settings.

The dynamic video ID is implemented like this:

<iframe src="http://player.vimeo.com/video/<?php echo $videoID; ?>?title=0&amp;byline=0&amp;portrait=0" width="400" height="225" frameborder="0"></iframe>

My question is, is there a way to detect the correct aspect ratio of the video?

I am aware of plugins like FitVids and methods using JavaScript as explained on CSS-Tricks to maintain aspect ratio for fluid widths, but they require setting the correct ratio initially with width and height attributes.

While newer Vimeo videos are typically width="400" height="225", older videos on my website have different ratios resulting in black bars either horizontally or vertically. I want to eliminate these black bars on all videos.

Any suggestions would be appreciated,

Alsweet

Answer №1

Obtaining the measurements

If you want to find out the dimensions, consider using the oEmbed API. With oEmbed, you can display embedded content by sending a HTTP request to the service endpoint. For instance:

An example of a request

http://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=NWHfY_lvKIQ

In return, you will receive a JSON response containing video dimensions and other helpful details.

A sample response:

{
    "title": "Learning from StackOverflow.com", 
    "height": 270,
    "author_url": "http:\/\/www.youtube.com\/user\/GoogleTechTalks",
    "author_name": "GoogleTechTalks",
    "provider_name": "YouTube",
    "thumbnail_url": "http:\/\/i.ytimg.com\/vi\/NWHfY_lvKIQ\/hqdefault.jpg",
    "html": "\u003ciframe width=\"480\" height=\"270\" src=\"http:\/\/www.youtube.com\/embed\/NWHfY_lvKIQ?feature=oembed\" frameborder=\"0\" allowfullscreen\u003e\u003c\/iframe\u003e",
    "provider_url": "http:\/\/www.youtube.com\/",
    "thumbnail_width": 480,
    "width": 480,
    "thumbnail_height": 360,
    "version": "1.0",
    "type": "video"
}

For more information, refer to the full documentation on the oEmbed website. This API offers a standardized way to access embedded content and is supported by various popular services such as YouTube, Vimeo, Flickr, and others.

Correctly showcasing the video

Utilize the width and height data provided by oEmbed to set your own width and height according to your requirements.

If your website requires responsiveness, there are plugins available to help in maintaining aspect ratio during resizing.

Alternatively, you could opt for a pure CSS approach. By using the width and height values obtained from oEmbed, follow these steps:

You can encapsulate the embed code within a parent div, set the iframe or object to 100% width and height, and create another nested div inside the parent to control the container's height. This inner div would have a padding-top value based on a percentage, say 60%, resulting in the main container adapting its height to be 60% of its width. Calculate the padding amount using the height as a percentage relative to the width provided by oEmbed.

Sample HTML snippet

<div class="video">
    <span class="video-height"></span>
    <iframe src="https://www.youtube.com/embed/NWHfY_lvKIQ" frameborder="0">   </iframe>
</div>

Sample CSS snippet

.video {
    width: 50%;
    position: relative;
}

.video > .video-height {
    padding-top: 60%;
    display: block;
}

iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

Experience a live demonstration here: https://jsfiddle.net/k2eyty4f/3/. Try resizing the window to witness how the height adjusts automatically based on the width percentage.

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

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

Expand the background of columns to cover grid gutters

Imagine this... You're working on a layout with three columns, all within a fixed-sized container that is centered using margin:0 auto. The design requires the first column to have a background color that reaches the left edge of the browser window. ...

What are some ways to create a div section within a Google Map interface?

Is there a way to create a div area within the Google map iframe? Some of my code is already prepared here (). The image in this link () illustrates exactly what I'm trying to achieve. ...

Unfortunately, CSS3 PIE is not compatible with border-radius and box-shadow properties

I created a basic HTML/CSS code for testing purposes, but I'm having trouble getting the library to function properly. I've placed the .htc, .php and .js files in the same directory as index.html, but it just won't work. Check out the code ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...

Disabling dates in the second datetimepicker depending on following days selected in the first one

I have implemented the bootstrap date picker and I am using two textboxes for searching by date range. I want the second textbox to display the days after the date selected in the first textbox. Any suggestions would be appreciated. Here is the HTML code: ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

Issue encountered during JSON file extraction (Firefox)

Within my Node.js application, there is a specific route where I retrieve a large JSON dataset from a Postgres database and then send it in a compressed format as a response. To accomplish this, I utilize the Zlib module to compress the data using gzip. Be ...

What is the proper way to encode image URLs for use in CSS?

For the div element in my code, I want to allow users to input a URL that will be applied as a CSS background image, like this: background-image: url("/* user specified URL here*/") I'm concerned about security. How can I properly escape the URL to ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

adjusting the size of the sidebar at the top to ensure that it does not overlap the top menu

I have a sidebar on my page that opens vertically when I click a button. The sidebar covers the company logo and name, so I want to make it smaller. Here is the code for the sidebar: <body> <nav class="navbar navbar-dark bg-dark" ...

I'm just starting to dabble in Perl and am curious about a few things regarding regular expressions

I am currently teaching myself Perl and find that examples are the most effective way for me to learn. Right now, I am delving into a basic Perl script that scrapes a specific blog and have encountered some confusion regarding a few of the regex statements ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

I am currently in the process of conducting an automated test focused on the creation of a new Facebook account

I am currently facing a challenge while attempting an automated test on Facebook. The issue lies in clicking the "Create Account" button using FindElement by id, which is not functioning as expected. public void createAccount(String firstName, String lastN ...

Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class: <div class="customTimer"></div> Here is the corresponding CSS code: .customTimer { width: 100%; height: 1 ...