调整图像大小以适应div +保持比率+水平和垂直居中+圆角

问题:

  1. 调整图像大小以适应div – 已解决
  2. 保持比例 – 解决
  3. 水平和垂直居中 – 解决了
  4. 圆角

    a)矩形图像 – 解决

    b)横幅图片 – !!! impossiburu !!!

所以问题是:我如何摆脱图像的矩形角落? 请看这里看问题: >>> http://jsfiddle.net/infoman/5fzET/3/ <<<

换句话说:图像的角落是圆形的,但它们不在div的末端,而是超出它。 我需要在div结束的行处对图像进行舍入。

HTML

test image ratio w/h = 4 

test image ratio w/h = 0.25

test image ratio w/h = 1 but small

test image ratio w/h = 1 perfect fit

test image ratio w/h = 1 much too big

CSS

 div { border: solid 1px green; width: 300px; height: 300px; overflow: hidden; border-radius: 10px; } div img { outline: solid 1px red; } .fillwidth { width: 100%; height: auto; position: relative; /*top*/ } .fillheight { height: 100%; width: auto; position: relative; /*left*/ } .fillfull { height: 300px; width: 300px; } 

jQuery的

 $('img[id^="myimg"]').each(function() { var imgWidth = $(this).width(), imgHeight = $(this).height(), imgRatio = imgWidth / imgHeight, imgWidthTop = (((300 / imgWidth) * imgHeight) / 2) * -1 + 300 / 2, imgHeightLeft = (((300 / imgHeight) * imgWidth) / 2) * -1 + 300 / 2; switch (true) { case (imgRatio === 1): $(this).addClass('fillfull'); break; case (imgRatio  1): $(this).addClass('fillheight'); $(this).css('left', imgHeightLeft); break; default: break; } });​ 

尝试和失败:

  1. 剪辑: http : //jsfiddle.net/infoman/5fzET/4/

尝试:

 border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; 

您可以将其添加到div和图像中。

更简单的解决方案

在这里演示: http : //jsfiddle.net/EdHQh/

HTML:

 

CSS:

 .container { width: 115px; height: 115px; line-height: 115px; text-align: center; border: 1px solid orange; } .resize_fit_center { max-width:100%; max-height:100%; vertical-align: middle; border-radius: 20px; -moz-border-radius: 20px; -webkit-border-radius: 20px; } 

这是你的答案的开始。 下面的代码显示了如何设置图像父元素的类(这是您需要的)。

 $('img[id^="myimg"]').each(function() { var imgWidth = $(this).width(), imgHeight = $(this).height(), imgRatio = imgWidth / imgHeight, imgWidthTop = (((300 / imgWidth) * imgHeight) / 2) * -1 + 300 / 2, imgHeightLeft = (((300 / imgHeight) * imgWidth) / 2) * -1 + 300 / 2; // alert(imgRatio); switch (true) { case (imgRatio < 1.1 && imgRatio > .99): $(this).addClass('fillfull'); break; case (imgRatio < 1): $(this).addClass('fillwidth'); $(this).css('top', imgWidthTop); //$(this).css('clip', 'rect(100px 0 100px 0)'); $(this).parent().addClass('bev'); break; case (imgRatio > 1): //$(this).css('clip', 'rect(0 100px 0 100px)'); $(this).addClass('fillheight'); $(this).css('left', imgHeightLeft); $(this).parent().addClass('bev'); break; default: break; } }); 

  .bev { border: solid 1px green; width: 300px; height: 300px; overflow: hidden; border-radius: 10px; margin-left: 10px; } div img { outline: solid 1px red; } .fillwidth { width: 100%; max-height: 99999px; position: relative; /*top*/ } .fillheight { height: 100%; max-width: 99999px; position: relative; /*left*/ } .fillfull { height: 300px; width: 300px; } 

你可以让serval不同的类有不同的角落,或者你可以使用javascript来改变样式属性。 我希望这有帮助