我的這種方法是使用該圖像作爲背景圖像。這將使您能夠對其進行居中並在調整大小時對其進行裁剪,同時仍然保持所需的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