Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 01 Apr, 2021
Geek Week

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:

  • Here we will use CSS inside the tags which are also known as inline CSS.
  • For parent div we will give fixed size by giving height: 500px and width: 40% according to screen size, and we will give it background color and border to clearly make the parent visible.
  • Now for the child image, we will give width: 60% and height: 70%.

HTML




<!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:



  • Here we will write the CSS in style tag also known as inline CSS.
  • Now we will give the parent fixed size by giving it height: 500px and width: 40% and to define the parent clearly we will give border-color and background-color.
  • Finally, we will give the image width: 50% and height: 45%.

HTML




<!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:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :