Resize image proportionally with CSS?

2018-12-31 21:20发布

Is there a way to resize (scale down) images proportionally using ONLY CSS?

I'm doing the JavaScript way, but just trying to see if this is possible with CSS.

18条回答
骚的不知所云
2楼-- · 2018-12-31 21:33

I believe this is the easiest way to do it, also possible using through the inline style attribute within the <img> tag.

.scaled
{
  transform: scale(0.7); /* Equal to scaleX(0.7) scaleY(0.7) */
}

<img src="flower.png" class="scaled">

or

<img src="flower.png" style="transform: scale(0.7);">
查看更多
听够珍惜
3楼-- · 2018-12-31 21:34

Notice that width:50% will resize it to 50% of the available space for the image, while max-width:50% will resize the image to 50% of its natural size. This is very important to take into account when using this rules for mobile web design, so for mobile web design max-width should always be used.

查看更多
栀子花@的思念
4楼-- · 2018-12-31 21:35

If it's a background image, use background-size:contain.

Example css:

#your-div {
  background: url('image.jpg') no-repeat;
  background-size:contain;
}
查看更多
还给你的自由
5楼-- · 2018-12-31 21:35

Revisited in 2015:

<img src="http://imageurl" style="width: auto; height: auto;max-width: 120px;max-height: 100px">

I've revisited it as all common browsers now have working auto suggested by Cherif above, so that works even better as you don't need to know if image is wider than taller.

older version: If you are limited by box of 120x100 for example you can do

<img src="http://image.url" height="100" style="max-width: 120px">
查看更多
还给你的自由
6楼-- · 2018-12-31 21:37

You can use object-fit property:

.my-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
}

This will fit image, without changing the proportionally.

查看更多
倾城一夜雪
7楼-- · 2018-12-31 21:38
img{
    max-width:100%;
    object-fit: scale-down;
}

works for me. It scales down larger images to fit in the box, but leaves smaller images their original size.

查看更多
登录 后发表回答