Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create proportional image height/width

Tags:

So, I want to have an image resized to 30% of its original height/width. Pretend you don't know its height or width, how would you go about it using only CSS/HTML?

like image 670
PizzaPie Avatar asked Aug 01 '10 00:08

PizzaPie


People also ask

How do you scale a photo proportionally?

If the Shift key is held down whilst moving the handle, then the proportions of the object will be preserved. For example, if I hold Shift and drag the bottom edge upwards to reduce the size by half, then the right edge will automatically move to the left to reduce the width of the object by the same amount.

How do you make a picture the same width and height?

container { width: 50%; } . container img { width: 100%; height: 400px; //this should be the same as the width value.. }

How do you scale a proportionally image in CSS?

In that situation we can use CSS max-width or width to fit the image. Use max-width: 100% to limit the size but allow smaller image sizes, use width: 100% to always scale the image to fit the parent container width.


2 Answers

If you need a quick inline solution:

<img style="max-width: 100px; height: auto; " src="image.jpg" /> 
like image 103
Blum Avatar answered Sep 22 '22 05:09

Blum


Update:

Using a display: inline-block; wrapper, it's possible to make this happen with CSS only.

HTML

<div class="holder">     <img src="your-image.jpg" /> </div> 

CSS

.holder {      width: auto;   display: inline-block;     }  .holder img {   width: 30%; /* Will shrink image to 30% of its original width */   height: auto;     }​ 

The wrapper collapses to the original width of the image, and then the width: 30% CSS rule on the images causes the image to shrink down to 30% of its parent's width (which was its original width).

Here's a demo in action.


Sadly no pure HTML/CSS way to do it as neither is geared to perform calculations like that. However, it's pretty simple with a snippet of jQuery:

$('img.toResizeClass').each(function(){      var $img = $(this),         imgWidth = $img.width(),         imgHeight = $img.height();      if(imgWidth > imgHeight){         $img.width(imgWidth * 0.3);     } else {         $img.height(imgHeight * 0.3);     } }); 
like image 32
Pat Avatar answered Sep 23 '22 05:09

Pat