Open In App

How to set width and height of background image in percent with respect to parent element in CSS ?

If we are using an image as a child and want to set the height and width in percentage then we need to set the parent element with some fixed size.

Approach 1:



Example: In this example, we are using the above-explained approach.




<!DOCTYPE html>
<html>
<body>
    <div style="height: 500px; width: 40%;
                background-color: red;
                border-color: green;
                border-style: dashed;">
 
        <img src="gfg-2.png"
             alt="GFG"
             style="width: 60%; height: 70%">
    </div>
</body>
</html>

Output:



Approach 2:

Example: In this example, we are using the above approach.




<!DOCTYPE html>
<html>
<head>
    <style>
        /* giving parent fix size  */
         
        div {
            height: 500px;
            width: 40%;
            background-color: blue;
            border-color: black;
            border-style: dashed;
        }
        /* child having size in % */
         
        img {
            width: 50%;
            height: 45%;
        }
    </style>
</head>
<body>
    <div>
        <img src="gfg-2.png" alt="GFG">
    </div>
</body>
</html>

Output:


Article Tags :