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.