CSS image scaling to fit within area not distort

久未见 提交于 2019-12-18 12:46:37

问题


Is there a way with CSS or otherwise of making an image fit within an area. Lets say I have multiple images of different sizes and I want them all to fit within a div of 150px by 100px. I don't want to scale the images though as some may be tall and others narrow I simply want them to fit within this area with the rest hidden.

I thought about using overflow:hidden but it appears to not be hidden in IE6.

Any ideas?


回答1:


You should try using this:

img{
  width: auto;
  max-width: 150px;
  height: auto;
  max-height: 100px;
}

Edit: Looks like IE6 doesn't support max-width and max-height properties. However, you can implement the workaround given here: max-width, max-height for IE6

Excerpt (in case linked article stops working):

img {
  max-height: 100px;
  max-width: 100px;
  width: expression(document.body.clientWidth > 150? “150px”: “auto”);
  height: expression(document.body.clientHeight > 100? “100px”: “auto”);
}



回答2:


This won't work in IE6 (as required by the OP), but for completeness you can achieve the required effect on newer browsers using CSS3's background-size:cover and setting the image as a centered background image. Like so:

div { 
  width:150px;
  height:100px;
  background-size:cover; 
  background-position:center center; 
  background-repeat:no-repeat; 
  background-image:url('somepic.jpg');
}



回答3:


When you say "fit within this area" with the rest hidden I feel like you want the image to not be scaled down at all and basically crop off any excess.

I might be interpreting you're question wrong, but try this and see if it produces the effect you're looking for.

.img-holder {
  width: 150px;
  height: 150px;
  position: relative;
  overflow: hidden;
}
.img-holder img {
  position: absolute;
  display: block;
  top: 0;
  left: 0;
}
<div class="img-holder">
  <img src="http://img.playit.pk/vi/dH6NIe7wm4I/mqdefault.jpg" />
</div>



回答4:


This worked for me:

img.perfect-fit {
    width: auto;
    height: auto;
    min-width: 100%;
    min-height: 100%;
}

It tries to do a "perfect fit" of the container, stretching itself to fit the bounds while maintaining image proportion. Haven't tested it with IE6.

JSFiddle: http://jsfiddle.net/4zudggou/




回答5:


I know this is an old one, but because I found it in search of answer for the same question, I guess it could be of use for someone else, too.

Since the answers were posted, CSS property object-fit was brought to us. It does exactly what was once requested in the question.

For reference: https://www.w3schools.com/css/css3_object-fit.asp



来源:https://stackoverflow.com/questions/5369301/css-image-scaling-to-fit-within-area-not-distort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!