Resizing You Tube and HTML5 videos proportionally using CSS for responsive web design
This article demonstrates how video can be resized automatically to fit the width of its container using only CSS with appropriate aspect ratio. The current solution works for any video which is set in iframe, embed, object or video tags.
Here is a simple HTML code which YouTube provides for sharing its videos on other websites:
Just try to resize browser window to make sure that the video doesn't change its size relatively to browser window width:
Live demo
As can be seen above the video has a fixed size.
To make the video adjustable to its container width, its code (iframe tag in our case) must be placed inside div tag with class "video-responsive" then the appropriate styles must be added.
HTML code:
CSS code:
.video-responsive { position: relative; padding-bottom: 75%; height: 0; overflow: hidden; } .video-responsive iframe, .video-responsive object, .video-responsive embed, .video-responsive video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
Now the YouTube video above adjusts its size to its container width.
Live demo
Here is the main thing which you have to know about the styles above to fully use them for other videos.
Every video has its own aspect ratio. Standard aspect ratio for a video is 4:3, but nowadays a lot of videos are created in widescreen format with aspect ratio of 16:9. This fact has to be taken into consideration when you are going to use this solution. The styles above are developed for videos with aspect ratio of 4:3. If you want to use them for videos with 16:9 aspect ratio, you will need to replace the value of padding-bottom CSS property with the following padding-bottom: 56.25%;
.
Actually here is a formula to calculate the value of the padding-bottom property for a video with any possible aspect ratio:
height / width * 100
Calculations for current examples:
9 / 16 * 100 = 56.25 3 / 4 * 100 = 75
Now, it's clear how we got padding-bottom: 56.25%;
for aspect ratio of 16:9 and padding-bottom: 75%;
for 4:3 aspect ratio.
The current solution works in the same way for HTML5 videos as for YouTube videos.
Continue reading here: Great features for responsive web design using сalc in CSS3
Was this article helpful?
Readers' Questions
-
MARJA POKKA1 month ago
- Reply
-
WOLFGANG4 months ago
- Reply
-
Anja6 months ago
- Reply
-
Pimpernel Button8 months ago
- Reply
-
miika10 months ago
- Reply
-
pertti1 year ago
- Reply
-
sandra1 year ago
- Reply
-
Nannie1 year ago
- Reply