Open In App
Related Articles

How to set the div height to auto-adjust to background size?

Improve Article
Improve
Save Article
Save
Like Article
Like

Sometimes, while creating a website, it is required to make a div adjust its height automatically according to the background without having the need to set a specific height or min-height. It makes it convenient for the developer while writing the code. 

We’ll create an img element inside our div and will set its src same as that of our background image. It’s visibility will be set as hidden so that only the background image will appear. Set the background-repeat property of the div element to “no-repeat” so as not to repeat the image. 

Example:  Since the image is the background image of the div, therefore, the heading GeeksforGeeks appears over the image.

html




<!DOCTYPE html>
<html>
    <head>
        <title>Title of the document</title>
        <style>
            div {
                background-image: 
                background-repeat: no-repeat;
            }
            img {
                visibility: hidden;
            }
            h1 {
                position: absolute;
                left: 35%;
                top: 30%;
                color: white;
            }
        </style>
    </head>
    <body>
        <div>
            <h1>GeeksforGeeks</h1>
            <img src=
                 alt="Image" />
        </div>
    </body>
</html>


Output: 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 08 Jun, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials