The goal of this tutorial is to help you understand how to make images and videos responsive on your websites, ensuring they look good and function well on all devices (desktops, tablets, and mobile phones).
By the end of the tutorial, you will learn how to:
- Use CSS techniques to make images and videos responsive.
- Use HTML's <picture>
and <source>
elements for responsive images.
- Set video width and height properties.
You need to have a basic understanding of HTML and CSS. Familiarity with web design principles would be a plus but is not required.
Responsive design is a web design approach that makes your web content adapt to the different screen and window sizes of a variety of devices.
To make an image responsive, we will use CSS. The key is to set the max-width
of the image to 100%
. This way the image will scale down if it has to, but never scale up to be larger than its original size.
img {
max-width: 100%;
height: auto;
}
Videos can be made responsive in a similar way to images. By default, videos don't resize like images when the browser window is resized. We will use a container and then give it a relative
position, with the video inside it an absolute
position.
.video-container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
The padding-bottom
property for the .video-container
is derived from the aspect ratio of the videos (16:9), which is about 56.25%.
Here is an example of a responsive image:
<!DOCTYPE html>
<html>
<head>
<style>
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h2>Responsive Image</h2>
<img src="img_chania.jpg" alt="Flowers in Chania">
</body>
</html>
Here is an example of a responsive video:
<!DOCTYPE html>
<html>
<head>
<style>
.video-container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video-container video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="video-container">
<video controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</body>
</html>
In this tutorial, you have learned how to make images and videos responsive using CSS. You've seen how to use the max-width
property for images and position
, width
, and height
properties for videos to ensure they adapt to different screen sizes. For further learning, you could explore other aspects of responsive design, such as responsive typography or responsive grids.
padding-bottom
value accordingly.src
attribute with your own image and video URLs.padding-bottom
should be 75% (3/4 = 0.75 or 75%).Remember, practice is key to mastering any concept. Try creating your own images and videos and make them responsive. Happy coding!