Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS image max-width set to original image size?

Tags:

css

image

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!

like image 698
nikk wong Avatar asked Jun 13 '14 04:06

nikk wong


People also ask

How do I change the original size of a picture?

One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels. For example, the original image is 640×960.

How do I make an image responsive with max-width?

To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.

How do I fix the full width of an image in CSS?

Set the image's width to 100%, and the image's height will adjust itself: <img style="width:100%;" id="image" src="...">


1 Answers

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}
<div class="box1">      <img src="https://i.stack.imgur.com/FuQYf.png" alt="" />  </div>  <div class="box2">      <img src="https://i.stack.imgur.com/FuQYf.png" alt="" />  </div>
like image 161
Mr Lister Avatar answered Sep 18 '22 14:09

Mr Lister