CSS image scaling to fit within area not distort

2019-02-05 16:13发布

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?

4条回答
Viruses.
2楼-- · 2019-02-05 16:33

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/

查看更多
可以哭但决不认输i
3楼-- · 2019-02-05 16:34

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

查看更多
姐就是有狂的资本
4楼-- · 2019-02-05 16:41

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>

查看更多
唯我独甜
5楼-- · 2019-02-05 16:54

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');
}
查看更多
登录 后发表回答