2012-02-20 74 views

回答

0

用於定心件的簡單方法。試試這樣的:

.box { 
    display: block; 
    height: 500px; 
    width: 500px; 
    background-color: #eee; 
    margin:0; 
    padding:0; 
    vertical-align:center; 
} 


.center_item { 
    display: block; 
    height: 100px; 
    width: 100px; 
    background-color: #aaa; 
    margin:0 auto; 
    padding:0; 
} 

和相應的HTML。

<div class="box"> 
    <div class="center_item">Put your image here.</div> 
</div> 

這樣做是僅僅把容器周圍無論你需要爲中心。通過使用margin:0 auto;您可以將任何項目置於其父項中間。我希望這是你正在尋找的。

0

jsBin demo

在這個例子中,我們使用text-align:center;我們的元素#gallery 和強制圖片是100%高度。
jQuery的我們檢查​​的形象,看是否圖像寬度超過廊寬度。在這種情況下,我們將使用jQuery更改寬度和垂直中心對齊方式。 E.g:

CSS:

#gallery{ 
    position:relative; 
    margin:0 auto; 
    width:600px; 
    height:500px; 
    border:1px solid #aaa; 
    text-align:center; 
    } 
    #gallery img{ 
    height:100%; 
    } 

的jQuery:

$('#gallery img').load(function(){ 

    img = $(this); 
    imgW = img.width(); 

    if(imgW > $('#gallery').width()){ 
    img.css({width:'100%', height:'auto'}); 
    img.css({marginTop: $('#gallery').height()/2 - $(this).height()/2 }); 
    } 

}); 

播放與圖像寬度/高度,看看他們如何迴應。