CSS resize div whilst maintaining aspect ratio of containing image

Viewed 107

I have a div container with an img inside of it:

<div id='triangle'>
     <img src='/static/triangle.png' style='position: absolute; height: 100%; width: 100%'>
</div>

How would I resize the div to a height of 500px and keep the aspect ratio? I have tried:

#triangle 
{
     position: absolute;
     height: 500px;
     width: auto;
}

but it does not work: Alternatively:

#triangle 
{
     position: absolute;
     max-height: 500px;
     max-width: 500px;
}

Creates a div of 500x0 px.

3 Answers

you should Remove "Position: absolute" from image tag. because parent already styled with position: absolute;

Try to apply this style and remove inline-styling from element:

#triangle {
    height:500px;
    width: max-content;
}

img {
    height:100%;
}

What you need to do is making one of the width or height attributes of the img tag equal to 100% and the other one equal to auto based on your needs.

Also your img tag must not have position:absolute feature. Therefore, your code should look like:

<!DOCTYPE html>
<html>
    <head>
        <style>
            #triangle 
            {
              position: absolute;
              height: 500px;
              width: 500px;
            }
        </style>
    </head>
    <body>
        <h2>HTML Image</h2>
        <div id="triangle">
            <img src='/static/triangle.png' width="100%" height="auto">
        </div>
    </body>
</html>
Related