5

Is there a way to resize images retaining their proportions with CSS?

The container has a fixed width and height

<div class="container">
   <img class="theimage" src="something" />
</div>

and the reason I'm asking is because the layout can change (from list to icons via a class) and the images need to be resized (about 40% less) in proportion.

I know how to do it with JavaScript and also how to resize via CSS, but don't really believe it can be done in proportion with CSS, unless there is some clever way.

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
jackJoe
  • 11,078
  • 8
  • 49
  • 64

2 Answers2

6
.theimage{
    width:100%;
    height:auto;
}

or

.theimage{
    width:auto;
    height:100%;
}

Depending on how you wanna give the scale preference... :) :)

Thats all.

Arindam Paul
  • 378
  • 1
  • 2
  • 10
  • 1
    but that doesn't solve the issue, I don't know the proportion of every image and so I can't set just one to 100%, just check my example at jsfiddle and try for yourself. – jackJoe Mar 08 '11 at 11:03
  • Are you saying loosing aspect ratio is fine with you ... only thing that concerns you, is to fit the image in that div?? If not then one of the above will solve your problem depending on which one becomes bottleneck for you.. is it the width or height... But if it is otherwise .. just use width:100%, height:100%... http://jsfiddle.net/arindam89/fDNah/12/ – Arindam Paul Mar 08 '11 at 13:01
  • 1
    no, I need to retain the proportion (check the title of this question), and this is not javascript I can't find out wich is the biggest (the height or the width), so that CSS you suggested won't work for me, do you see my problem? – jackJoe Mar 14 '11 at 10:10
5

To save the Image ratio while scaling you can use object-fit CSS3 propperty.

Useful article: Control image aspect ratios with CSS3

img {
    width: 100%; /* or any custom size */
    height: 100%; 
    object-fit: contain;
}
Andrii Verbytskyi
  • 7,155
  • 3
  • 47
  • 38