Responsive Embedded Videos
Page Speed ChecklistScaling Fixed-Proportion <iframe>s
Create an element with a proportion that matches the video and then size and position the video <iframe>
to fill that space.
The HTML
Start with a container around the video <iframe>
.
<div class="video">
<iframe src="https://www.youtube.com/embed/videoID" title="Video Title"></iframe>
</div>
(Always include a title
attribute for accessibility.)
The CSS
Top or bottom padding
sets the proportion - for example 56.25% for the common 16:9 aspect ratio - and the <iframe>
is positioned and sized to fill the container.
/*--- video container ---*/
.video {padding-bottom:56.25%;position:relative}
/*--- <iframe> ---*/
.video iframe {width:100%;height:100%;position:absolute}
The above CSS works for videos that span the full width of their parent element. For fixed or relative width videos - like width:50%
in a two-column layout - set the padding on a pseudo element, rather than directly on the container.
/*--- video container ---*/
.video {position:relative}
/*--- pseudo element ---*/
.video::before {display:block;padding-bottom:56.25%;content:""}
/*--- <iframe> ---*/
.video iframe {width:100%;height:100%;position:absolute}
Live Example
On-Demand Embedded Videos
This example above also uses a technique to load embedded YouTube videos on demand to reduce initial-load page weight and improve page speed:
On-Demand Embedded Videos