How to set an equivalent of the \"cover\" Value of the background-size Property for an img Tag?



When creating responsive images in web design, a common requirement is to make the image fill the entire container while preserving its aspect ratio. Traditionally, the background-size: cover; CSS property is used with background images to achieve this effect. However, for inline images (using the <img> tag), there is a different approach using the object-fit property. This article will walk you through setting up this equivalent effect on an <img> tag, along with a comparison between using an <img> element and a background image.

Approach

Using object-fit: cover with Tags

The object-fit CSS property is designed to control how content fills a container. Using object-fit: cover; on an <img> tag achieves the same effect as background-size: cover for background images, ensuring the image fills the container and retains its aspect ratio.

Example Code

In the following example, we set up an image to occupy the full viewport width and height. We use object-fit: cover to make sure the image fills the entire container while maintaining its aspect ratio.

<!DOCTYPE html>
<html>

<head>
    <title>Using object-fit for Cover Effect</title>
    <style>
        body {
            margin: 0;
        }

        img {
            display: block;
            width: 100vw;
            height: 100vh;
            object-fit: cover;
        }
    </style>
</head>

<body>
    <img src=
"https://www.tutorialspoint.com/static/images/hero.png" 
         alt="Cover Image Example" />
</body>

</html>

Output

Cover Image Example

Using Background Images as an Alternative

In some cases, you may prefer to use a background image instead of an inline <img> tag. This is common when the image is purely decorative or does not need to be part of the document's content structure. Here's how you can achieve a similar effect using a background image and background-size: cover;.

Example Code

In this example, we use an element as a placeholder but set the actual image as a background image in CSS. We also use padding to control the size of the image container.

<!DOCTYPE html>
<html>
<head>
    <title>Background-size Cover Example</title>
    <style>
        body {
            margin: 0;
        }
        
        .background-img {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100vh;
            background: url(
'https://www.tutorialspoint.com/static/images/hero.png') no-repeat center center;
            background-size: cover;
        }
    </style>
</head>
<body>
    <div class="background-img"></div>
</body>
</html>

Output

Cover Image Example

Updated on: 2024-11-08T11:24:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements