CSS image max-width set to original image size?

前端 未结 2 1140
灰色年华
灰色年华 2020-12-22 23:16

Can you do this? I\'m having users upload images into a container that is width:100%, but I don\'t want the images to be larger than their original size. Many thanks!

2条回答
  •  無奈伤痛
    2020-12-23 00:10

    Just don't set the width of the image, only the max-width.

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

    (height:auto is not really necessary, since auto is the default, but I put it in there as a reminder to myself that I want the image to have its natural proportions.)

    This snippet has two boxes, one that is smaller than the image and one that is larger. As you can see, the image in the smaller box gets scaled down, while the one in the bigger box has its normal size.

    div {border:2px outset green; margin:6px 0}
    .box1 {width:100px; height:70px;}
    .box2 {width:200px; height:100px;}
    img {max-width:100%; height:auto}

提交回复
热议问题