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 the parent div we will give a 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 a width: 60% and a height: 70%.
Example: In this example, we are using the above-explained approach.
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 a 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%.
Example: In this example, we are using the above approach.
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:
