background-size: cover`と同じように、ボックス内の画像のサイズを変更したり、ボックス全体を覆うように再配置するにはどうしたらよいでしょうか。
<div class="box" style="width: 100px; height: 100px;">
<img src="pic.jpg" width="413" height="325">
</div>
ボックスには overflow:hidden
を追加する必要があり、画像には position:absolute
が必要なのはわかっています。しかし、画像の正しい新しいサイズと、左と上の位置を得るための公式は何でしょうか?
**この方が簡単かもしれません。
jQuery
$('.box').each(function() {
//set size
var th = $(this).height(),//box height
tw = $(this).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if (ih>iw) {//if portrait
im.addClass('ww').removeClass('wh');//set width 100%
} else {//if landscape
im.addClass('wh').removeClass('ww');//set height 100%
}
//set offset
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (nh<nw) {//if portrait
im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
} else {//if landscape
im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
}
});
css
.box{height:100px;width:100px;overflow:hidden}
.wh{height:100%!important}
.ww{width:100%!important}
これはどのようなサイズ/方向にも対応し、リサイズだけでなく画像のオフセットも行います。すべて、相対的
や絶対的
な位置関係ではありません。
作ってみた:
https://developer.mozilla.org/en-US/docs/Web/CSS/background-size から。
cover
This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.
つまり、width: 100%
かheight: 100%
のどちらかにして、親のdiv
の中で重なりを作ることになります。そこで、次のようなロジックにします。
var makeBackgroundCover = function (div) {
$(div + " img").css("height", "100%");
if ($(div + " img").width() < $(div).width()) {
$(div + " img").css({
"height": "auto",
"width": "100%"
});
}
}
次のフィドルでは、この関数が水平と垂直の両方の画像に対して動作することを示しています。
画像をリサイズせずにボックスの中央に配置したい場合は、このコードを使うだけです。
.box {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.box img {
width: 413px;
height: 325px;
position: absolute;
left: 50%;
top: 50%;
}
画像のサイズを変更して収める場合は、次のコードを使用します。
.box {
width: 100px;
height: 100px;
}
.box img {
width: 100%;
height: auto;
}
このコードは、画像の幅が高さよりも広い場合に、若干の余白を残します。 どちらもうまくいかない場合は、画像を背景として設定し、background-size: cover;
とすることもできます。