Scale image with CSS but limit to orignial size

2019-02-26 00:56发布

For a responsive design, i would like to scale down some images:

img {
    width:100%;
    height:auto;
}

This works as expected, but if the width of the screen exceeds the original size of the image, it blows up the image.

Is there a way to limit this scaling to its original size? So that it only gets smaller if necessary?

Thanks in advance for your answer.

Willem

2条回答
We Are One
2楼-- · 2019-02-26 01:39

Put the images in a <div> and give that <div> a max-width.

CSS

#test {
    max-width: 400px;
}
img {
    width:100%;
    height:auto;
}

HTML

<div id="test">
    <img src="http://a.dilcdn.com/bl/wp-content/uploads/sites/8/2012/09/02-11.jpg" />
</div>

JSfiddle

查看更多
混吃等死
3楼-- · 2019-02-26 01:44

You could use max-width to prevent image width from becoming larger than original size.

img {
    width: auto;
    max-width: 100%;
    height: auto;
}
查看更多
登录 后发表回答