图像无拉伸或裁剪 [英] Image No Stretch or crop
问题描述
我的问题很简单。假设我有两个矩形图像。第一个是200px宽,100px高,第二个是100px宽和200px高。
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.
我想显示具有恒定宽度/高度的图像,例如150px乘150px而不拉伸图像以适合:
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.
以下CSS将图像拉伸到适合150px乘150px:
The following CSS stretches the images to fit to 150px by 150px:
img {
width: 150px;
height: 150px;
}
最优选的解决方案是CSS,即使我需要更多标记。 JS / jQuery也没关系。
The most preferable solution is CSS, even if I need a little more markup. JS/jQuery is okay as well though.
推荐答案
怎么样:
img {
max-height:150px;
max-width:150px
}
要完成关于制作的第二个问题更小的图像更大,你可以用jQuery做。如果您事先知道照片方向并且对这些图像应用了不同的css类,那么CSS可以工作......但是这样可以工作,然后您不再需要CSS最大宽度的东西了。
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>
这篇关于图像无拉伸或裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!