我的这种方法是使用该图像作为背景图像。这将使您能够对其进行居中并在调整大小时对其进行裁剪,同时仍然保持所需的300像素高度。
DEMO http://jsfiddle.net/NSS2T/4/
div {
height: 300px;
max-width: 100%;
background: url('myImage.jpg') center center;
}
编辑
由于使用的是编程方式生成的图像,则需要通过jQuery作为并列的CSS实施例I上面已经给添加计算的造型。
DEMO http://jsfiddle.net/NSS2T/3/
HTML
<div>
<img src="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/3/10/1394464252285/5a3508c4-7dd0-4bac-90ed-f13c11b53cef-460x276.jpeg" class="upload" />
</div>
CSS
// this will offset the image by 50%
img {
display: block;
position: absolute;
left: 50%;
}
jQuery
// this will loop through all images with a class of .upload and then apply a calculated margin offest to center the image
var imgWidth;
$('img.upload').each(function() {
imgWidth = $(this).width()/2;
$(this).css('margin-left', '-'+imgWidth+'px');
});
这是不错,但我必须从程序指定图像的来源,是他们的一种方式,我们可以使用CSS我的HTML代码做到这一点。 – Learning