Home > OS >  How to fix the CSS/HTML image aspect ratio fixed across different monitors?
How to fix the CSS/HTML image aspect ratio fixed across different monitors?

Time:11-28

Whenever I use the following codes, the aspect ratio of my square-shaped image (1:1 aspect ratio) changes across different devices (different types of monitors/mobile phones)? When I say changes, on some devices it's a perfect square image as I'd expect but on some devices it becomes a rectangle. Does anyone know how to fix this? I want it to have the original aspect ratio.

<div > <img src="images/myimg.jpg" style="width: auto; height: 310px; margin-top: -190px; padding-left: 50px;"
             alt="Placeholder image"> </div>
<div > <img src="images/myimg.jpg" style="width: 310px; height: 310px; margin-top: -190px; padding-left: 50px;"
             alt="Placeholder image"> </div>

.img-fluid { max-width: 100%, height: auto }

It's a static website hosted on github pages.

Try different options. I was expecting it to preserve its original aspect ratio.

CodePudding user response:

You can try by giving width & height 100% to the image and limiting the parent div. By this it will always take the width and height available to it but not exceeding the max-width & max-height regardless of the device.

.img-container {
  width: 100%;
  height: 100%;
  max-width: 310px;
  max-height: 310px;
}

.img-container img {
  width: 100%;
  height: 100%;
}
<div > <img src="https://images.unsplash.com/photo-1495615080073-6b89c9839ce0?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=906&q=80"  alt="Placeholder image"> </div>

CodePudding user response:

.myImg {
  display: block;
  max-width:120px;
  max-height:210px;
  width: auto;
  height: auto;
}
<p>This photo is originally 500 pixels, but should get resized by the CSS</p>
<img  width="400" height="400" src="https://i.imgur.com/nOBDgBx.png">

  • Related