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?
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.
container { width: 50%; } . container img { width: 100%; height: 400px; //this should be the same as the width value.. }
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.
If you need a quick inline solution:
<img style="max-width: 100px; height: auto; " src="image.jpg" />
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); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With