[英]How to center an overflowing image inside of a constraining div
我有一個240x240px的div
,其中包含大小不一的圖像的幻燈播放。 我將每個圖像設置為一個height: 240px
,寬度根據其高度自動調整。 有些圖像比寬(按比例)高,因此我使用position: relative; margin: 0 auto
在div
居中position: relative; margin: 0 auto
position: relative; margin: 0 auto
除了圖像溢出 240px div
之外,這效果很好。 我如何才能將圖像集中在溢出的div
中? 我嘗試了此(jQuery),但由於某種原因無法正常工作,我確定自己無法弄清楚:
if( $("div img").width() > 240 ) {
$(this).css("margin-left", rv);
var rv = -1 * ($(this).width() / 4) + "px";
}
邏輯是,如果圖像將div
的寬度擴大,則將其向左移動rv
px, rv
為圖像寬度的1/4(因為1/2會將圖像裁剪為左側的一半,所以1 / 2 of 1/2有效居中嗎?)我的第一個猜測是,盡管我不知道,但我無法像嘗試那樣引用$(this)
。
我知道我可以添加單獨的內聯CSS樣式,但這很雜亂。 我寧願有一個腳本,該腳本可以自動計算圖像的中心,然后相應地移動它。 有任何想法嗎?
您只能使用CSS:
.imgHolder{
border:1px solid #000;
width:240px;
height:240px;
line-height:240px; /* same as element height */
font-size:0; /* to perfectly vertical align middle the image */
text-align:center; /* to horizontally align middle the image */
}
.imgHolder > img{
max-width:100%;
max-height:100%;
vertical-align:middle;
}
遍歷圖像,並在它們加載后獲得圖像寬度和父元素寬度,比較寬度,如果圖像比父元素寬,則獲得一半的差值,並從左邊緣減去該差值以將圖像水平居中。
$("div.centered img").each(function(_,el) {
var img = new Image(),
parent = $(el).parent();
img.onload = function() {
var ma = this.width - $(parent).width();
if ( ma > 0 ) {
$(el).css('margin-left', ((ma/2) * -1));
}
}
img.src = this.src;
if (img.complete) img.onload();
});
我建議這樣的事情:
div.center-img { background:url('/path/img.jpg') center center no-repeat; }
但是您的問題將通過以下方式得到回答:
$('div img').each(function() {
if( this.width > 240 )
$(this).css("margin-left", ((this.width - 240) / -2) + "px");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.