Dritz
Dritz

Reputation: 117

How to keep image the same size on HTML when image changes

I am trying to include two images in my webpage. One image stays the same, the other one will change, and it will change to images that has a different aspect ratio.

I want the image that will change to always be the same height as the first image (the one that doesn't change). When I change the image to another image with a different aspect ratio then the images are no longer the same height.

I've tried using overflow:hidden as I thought it would just crop out the overflowing areas of the image. I looked into using flex but as the aspect ratio keeps changing I didn't think it would be appropriate.

This is my HTML:

<html>
    <head></head>
    <body>
        <div>
            <img id="img1" src="https://cdn.silodrome.com/wp-content/uploads/2013/09/iPhone-5.jpg">
            <img id="img2" src="https://i.kinja-img.com/gawker-media/image/upload/s--6tZPLps6--/c_scale,f_auto,fl_progressive,q_80,w_800/trrsg0bnoouitdhsoe0s.jpg"
        </div>
    </body>
</html>

And this is my CSS:

html {
  margin:0px;
  padding:0pc;
}

div {
  float: left;
  width: 70%;
}

#img1 {
  width: 20%;
}

#img2 {
  width: 78.5%;
}

I have created a codepen to demonstrate the issue.

I want to be able to change img2 to any image and it have the same height. I would also like it to always be in the center of the space for the second image but I'm sure that is something I can work out.

Upvotes: 0

Views: 6402

Answers (3)

Tyler Shannon
Tyler Shannon

Reputation: 309

You could change your css to this

#img1 {
  height: 400px; /* This value can be whatever */
}
#img2 {
  height: 400px; /* This value can be whatever */
}

this will keep the aspect ratio of the images and apply a fixed height to both of them. It's recommended to use pixels and not a percentage.

Upvotes: 1

Showrin Barua
Showrin Barua

Reputation: 1795

You can try this. I have given a fixed height to the height of the div and added some properties in #img1 and #img2. Hope it will be helpful to you.

html {
  margin:0px;
  padding:0pc;
}
div {
  float: left;
  width: 70%;
  height: 25vw;
}
#img1 {
  width: 20%;
  height: inherit;
  object-fit: cover;
  object-positon: center center;
}
#img2 {
  width: 78.5%;
  height: inherit;
  object-fit: cover;
  object-positon: center center;
}
<html>
  <head>
  </head>
  <body>
    <div>
      <img id="img1" src="https://cdn.silodrome.com/wp-content/uploads/2013/09/iPhone-5.jpg">
      <img id="img2" src="https://i.kinja-img.com/gawker-media/image/upload/s--6tZPLps6--/c_scale,f_auto,fl_progressive,q_80,w_800/trrsg0bnoouitdhsoe0s.jpg"
    </div>
  </body>
</html>

Upvotes: 2

Arthur S.
Arthur S.

Reputation: 482

Just set the width and height of the <img> to a fix value

<img src="example.gif" alt="Example" width="200" height="100">

Upvotes: 0

Related Questions