参见英文答案 >
Resize an image to fit in div5个
我有高度和宽度不同的div,并希望我的图像自动调整大小以100%填充这些div,然后当然居中.
我有高度和宽度不同的div,并希望我的图像自动调整大小以100%填充这些div,然后当然居中.
目前我的图像设置为宽度100%,然后使用下面居中的jQuery,但这仅适用于高度大于div的图像一旦调整大小.我将如何使其高度和宽度均为100%中心也..完全填充div(即使这意味着拉伸图像)!
谢谢.
$('img.shelf-img').each(function(i,item) { var img_height = $(item).height(); var top_margin = -(img_height / 2); $(item).css({ 'top': '50%','margin-top': top_margin }); });
解决方法
使用CSS将图像的宽度和高度都设置为100%,图像将自动拉伸以填充包含的div,而不需要jquery.
此外,您不需要将图像居中,因为它已经被拉伸以填充div(以零边距为中心).
HTML:
<div id="containingDiv"> <img src=""> </div>
CSS:
#containingDiv{ width: 200px; height: 100px; } #containingDiv img{ width: 100%; height: 100%; }
这样,如果您的用户禁用了javascript,图像仍将被拉伸以填充整个div宽度/高度.
要么
JQuery方式(SHRINK / STRETCH TO FIT – 包含WHITESPACE):
$('img.shelf-img').each(function(i,item) { var img_height = $(item).height(); var div_height = $(item).parent().height(); if(img_height<div_height){ //IMAGE IS SHORTER THAN CONTAINER HEIGHT - CENTER IT VERTICALLY var newMargin = (div_height-img_height)/2+'px'; $(item).css({'margin-top': newMargin }); }else if(img_height>div_height){ //IMAGE IS GREATER THAN CONTAINER HEIGHT - REDUCE HEIGHT TO CONTAINER MAX - SET WIDTH TO AUTO $(item).css({'width': 'auto','height': '100%'}); //CENTER IT HORIZONTALLY var img_width = $(item).width(); var div_width = $(item).parent().width(); var newMargin = (div_width-img_width)/2+'px'; $(item).css({'margin-left': newMargin}); } });
JQuery方式 – CROP TO FIT(NO WHESESPACE):
$('img.shelf-img').each(function(i,item) { var img_height = $(item).height(); var div_height = $(item).parent().height(); if(img_height<div_height){ //INCREASE HEIGHT OF IMAGE TO MATCH CONTAINER $(item).css({'width': 'auto','height': div_height }); //GET THE NEW WIDTH AFTER RESIZE var img_width = $(item).width(); //GET THE PARENT WIDTH var div_width = $(item).parent().width(); //GET THE NEW HORIZONTAL MARGIN var newMargin = (div_width-img_width)/2+'px'; //SET THE NEW HORIZONTAL MARGIN (EXCESS IMAGE WIDTH IS CROPPED) $(item).css({'margin-left': newMargin }); }else{ //CENTER IT VERTICALLY (EXCESS IMAGE HEIGHT IS CROPPED) var newMargin = (div_height-img_height)/2+'px'; $(item).css({'margin-top': newMargin}); } });