CSS

Responsive Images and Videos


Responsive Images

To make images responsive, you can use the max-width and height: auto properties. This ensures that the image scales down if the viewport is smaller than the image’s original size, but it doesn’t scale up beyond its original size.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Images Example - Codersmile</title>
    <style>
        img {
            max-width: 100%;
            height: auto;
        }
    </style>
</head>
<body>
    <h2>Responsive Images on Codersmile</h2>
    <img src="https://www.codersmile.com/images/sample-image.jpg" alt="Sample Image">
    <p>This image will scale down according to the size of the screen.</p>
</body>
</html>

In this example:

  • The img selector sets the max-width to 100% of its container and height to auto.
  • This ensures the image will not exceed the width of its container and will maintain its aspect ratio.

 

Responsive Videos

To make videos responsive, you can use a similar approach with the max-width and height: auto properties. However, wrapping the video in a container element and applying styles to the container ensures better control over the responsiveness.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Videos Example - Codersmile</title>
    <style>
        .video-container {
            position: relative;
            padding-bottom: 56.25%; /* 16:9 ratio */
            height: 0;
            overflow: hidden;
            max-width: 100%;
            background: #000;
        }

        .video-container iframe,
        .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <h2>Responsive Videos on Codersmile</h2>
    <div class="video-container">
        <iframe src="https://www.youtube.com/embed/your-video-id" frameborder="0" allowfullscreen></iframe>
    </div>
    <p>This video will scale according to the size of the screen while maintaining its aspect ratio.</p>
</body>
</html>

In this example:

  • The .video-container class uses padding to maintain the aspect ratio (16:9 in this case) and makes sure the container adjusts its size according to the screen width.
  • The iframe (or video) inside the container is set to fill the container entirely, ensuring it remains responsive.