Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

html - Constrain img to div and maintain aspect ratio?

I've tried everything I can find.

I'm trying to keep an image from overflowing outside the div that it is inside.

I've tried:

div.row #whoPic {
    object-fit: contain;
    max-width: 100%;
    max-height: 100%;
    overflow: hidden;
    max-width: auto;
    max-height: auto;
    max-width: 300px;
    max-height: 300px;
}

...and many variations of each of those values.

I've also tried targeting all img's, as well as targeting very precisely.

Please help me out. Going nuts here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In fact this question has been asked before.
Here: How do I auto-resize an image to fit a div container
Here: Make an image width 100% of parent div, but not bigger than its own width
Here: Contain an image within a div?
Here: How do I fit an image (img) inside a div and keep the aspect ratio?

Restrict the image with max-width and max-height both set to 100%.

.theContainer {
  width: 300px;
  height: 100px;
  background-color: lightblue;
}

.theContainer img {
  max-width: 100%;
  max-height: 100%;
}
<div class="theContainer">
  <img src="https://placehold.it/200x200">
</div>
<h3> The original image size is 200x200 </h3>
<img src="https://placehold.it/200x200">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...