1

500x500 の固定サイズの div があります。この div 内に、動的にできるイメージ タグがあります。正方形、長方形 (幅 > 高さ)、または垂直の長方形 (高さ > 幅) のサイズを持つことができることを意味します。問題は、この画像をつぶしたくないということです。画像の縦横比を維持したかったのです。画像サイズが 1000x250 の場合、500x125 にサイズ変更してから、この 500x500 ボックスの中央に配置します。サイズが 500x1000 の場合、サイズを 250x500 に変更し、左右に白い間隔で中央に配置します。

純粋にcssを使用してこれを行う簡単な方法はありますか、それともjavascriptが必要ですか? そしてどうやって?

これが私が今持っているものの構造です:

<div class="product-large" style="position: relative; overflow: hidden;"><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" alt=""><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" class="zoomImg" style="position: absolute; top: -236.43249427917618px; left: -188.05491990846681px; opacity: 0; width: 1024px; height: 714px; border: none; max-width: none;"></div>
4

3 に答える 3

1

垂直方向のセンタリング用に更新 - jQuery が必要です。

HTML

<div class="product-large">
    <img src="image1.jpg">
</div>
<div class="product-large">
    <img src="image2.jpg">
</div>

CSS

.product-large {
    width:500px;
    height:500px;
    border:1px red solid;
    position:relative;
}
.product-large img {
    max-width:500px;
    max-height:500px;
    width:auto;
    height:auto;
    position:absolute;
    top:50%;
    left:50%;
}

Javascript (jQuery)

$(".product-large img").each(function () {
    //get height and width (unitless) and divide by 2
    var hWide = ($(this).width()) / 2; //half the image's width
    var hTall = ($(this).height()) / 2; //half the image's height, etc.

    // attach negative and pixel for CSS rule
    hWide = '-' + hWide + 'px';
    hTall = '-' + hTall + 'px';

    $(this).addClass("js-fix").css({
        "margin-left": hWide,
            "margin-top": hTall
    });
});

新しいフィドル: http://jsfiddle.net/Asvdk/2/

于 2013-05-03T05:39:57.517 に答える
0

jQuery の使用を検討している場合は、ここでImgCenter jQuery プラグインを確認できます。

于 2013-05-03T06:14:41.710 に答える
0

私はあなたができると思います:

 #conatiner {
    line-height:500px;
    height:500px;
    width:500px;
}
#img {
  max-width: 100%;
  max-height:100%;
  display: block;
  margin: 0 auto;
  vertical-align: middle;
}

最小限の部分的な例: http://jsfiddle.net/cahs4/

垂直方向の配置はしませんでしたが、意味がわかります

于 2013-05-03T05:35:44.573 に答える