2013-05-03 32 views
0

我試圖在保持div內圖像的正確縱橫比並將其居中的同時對圖像進行居中。我有以下的HTML代碼:刷新頁面後圖像位置不正確

<div class="product-large" style="position: relative; overflow: hidden;"> 
    <img src="/images/store_logos/c48edfde4dfb95efb42c5bb474fc249a2bc84253.jpeg" alt="" class="js-fix" style="margin-left: 0px; margin-top: 0px;"> 
    <img src="/images/store_logos/c48edfde4dfb95efb42c5bb474fc249a2bc84253.jpeg" class="zoomImg" style="position: absolute; top: 0px; left: -3.3157894736842106px; opacity: 0; width: 500px; height: 760px; border: none; max-width: none;"> 
</div> 

隨着下面的JavaScript代碼居中圖像:

$(".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 
     }); 
    }); 
#main.product-detail .product-banner .product-large img 
{ 
    max-width:437px; 
    max-height:437px; 
    width:auto; 
    height:auto; 
    position:absolute; 
    top:50%; 
    left:50%; 
} 

#main.product-detail .product-banner .product-large { 
    background-color: #F3EFEA; 
    height: 437px; 
    width: 437px; 
} 

它適用於第一負載完全正常,但是第二次圖像位置或破裂(即:它沒有正確居中)。

對於一個工作示例,您可以檢查鏈接below,然後刷新頁面幾次。你會注意到圖像不是第2次/第3次居中。任何想法爲什麼?

+1

事實上,我注意到,當我打開頁面的第一時間,'.js-fix'的邊際不在那裏。但我可以問爲什麼你使用'javascript'來居中圖像?爲什麼不在'.product-large'上使用'text-align:center'並從img中刪除'position:absolute'? – LRA 2013-05-03 23:36:56

+0

什麼是'js-fix'類?我認爲它沒有被使用。 – cortex 2013-05-03 23:37:44

+0

@LRA我正在嘗試將圖片居中,但我不想打破寬高比,所以我認爲這會解決它 – adit 2013-05-03 23:39:29

回答

0

如果你沒有得到這個工作,我建議你只使用100%的CSS對齊使用表格單元方法。小的JavaScript始終是更好:)下面是如何做到這一點

http://jsfiddle.net/fMJDj/1

一個的jsfiddle而在小提琴代碼:

<div> 
    <img src="http://explodingdog.com/drawing/awesome.jpg" /> 
</div> 

div { 
    border: 1px solid red; 
    display:table-cell; 
    vertical-align: middle; 
    text-align: center; 
    height: 800px; 
    width: 800px; 
} 
img { 
    max-width:437px; 
    max-height:437px; 
}