Image No Stretch or crop
Solution 1
What about:
img {
max-height:150px;
max-width:150px
}
To achieve your 2nd question on making smaller images bigger, you can do with jQuery. CSS could work if you knew the photo orientation before hand and applied a different css class to those images... But this will work and then you don't need the CSS max-width stuff any more.
<div class="container"><img src="images/DSC_0470.JPG" alt="Rad Image" /></div>
<script>
$(document).ready(
function () {
$('.container img').each(
function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
if (theWidth < theHeight) {
$(this).height(150);
}
else {
$(this).width(150);
}
});
});</script>
Solution 2
You should be able to use the max-width
and max-height
properties, like so:
img {
max-width: 150px;
max-height: 150px;
}
This should constrain it to that box without stretching it.
If you want to make sure that each appears in a square box of size 150px
by 150px
, you could contain each image in a container div, and force them to be exactly that size:
<div class="container">
<img>
</div>
with the following CSS:
img {
max-width: 150px;
max-height: 150px;
}
.container {
width: 150px;
height: 150px;
}
Related videos on Youtube
apparatix
Updated on September 15, 2022Comments
-
apparatix about 1 year
My question is simple. Let's say I have two rectangular images. The first is 200px wide and 100px tall, and the second is 100px wide and 200px tall.
I want to display the images with a constant width/height, e.g. 150px by 150px without stretching the images to fit:
I don't mind having whitespace/padding around the images. The problem is that the images could be of any width and height, and I want to limit them to a square box without stretching them.
The following CSS stretches the images to fit to 150px by 150px:
img { width: 150px; height: 150px; }
The most preferable solution is CSS, even if I need a little more markup. JS/jQuery is okay as well though.
-
murgatroid99Do you want the image to increase to 150px if it is smaller than the box?
-
-
Mr. Alien almost 11 years+1, first 1 to answer correctly...but be sure next time you present your answer, atleast edit after you answer, provide relative reference links, code, and if you can than a fiddle too as a demo :)
-
Salman A almost 11 yearsPresentation of your answer matters!
-
apparatix almost 11 yearsIs there a way to ensure that an image smaller than 150px by 150px fills the space?
-
MikeSmithDev almost 11 yearsI don't think so purely with CSS unless you knew the orientation and could apply the right class to it. Have you tried a JS approach?
-
Matthew Simoneau almost 11 yearsDoes this solution not work in IE8, or am I doing something wrong?