CSS RWD - Videos
CSS RWD Videos
In responsive web design, its important to make sure videos are fitting properly to the layout. Videos should expand to fill the entire content area while keeping their original aspect ratio.
When a fixed width or height of a video is specified, it may cause layout issue in very large or very small screens, such as breaking page layouts, distorting the shape, or displaying black bars around the video. The black bars around the video are calledletterboxing(on top and bottom of the video),pillarboxing(on left and right of the video), andwindowboxing(on all sides of the video).
So, itβs important to use relative units for the width and height property such as percentage, instead of absolute values, such as pixels. Absolute values restrict the video getting responsive.
Responsive Videos Using width Property
To make an video scale according to screen size, we need to setwidthproperty of the video to 100% andheightto auto.
video {
width: 100%;
height: auto;
}Setting style in this way makes the video take up 100% of the width of its parent element, and the height will be adjusted to maintain the videoβs aspect ratio. This setup allows the video to scale with the screen size. However, on very large screens, the video may stretch beyond its natural width, making it appear distorted.
Example
In this example, the video displayed will scale according to screen size of output window. Run this code in CodesCompilerHTML Compilerto adjust output window width and verify.
Responsive Videos Using max-width Property
The above mentioned method has a drawback, on large screens the video will get stretched beyond itβs natural dimension. To prevent this, we can usemax-widthproperty instead of βwidthβ property.
video {
max-width: 100%;
height: auto;
}By setting video properties in this way, the video will scale down if it has to, but never scale up to be larger than its original size.
Example
In this example, the video displayed will scale according to screen size of output window but never scale more than itβs natural size. Run this code in CodesCompilerHTML Compilerto adjust output window width and verify.
Add a Video to the Example Web Page
The following example demonstrates the use of a responsive video in a webpage. Based on the max-width value of the video, the video gets scaled down as per the screen size.