2011-12-03 101 views
6

我有width:100%overflow:hidden
我需要放置的2500-3000px它裏面的圖像的父股利,但具有圖像水平方向上居中(裁剪左側和右側),以使主中心部的圖像顯示在較小的屏幕上,但沒有水平滾動條。
我不能使用background-image,因爲圖像是通過php動態添加的。
請幫忙。中心圖像水平內溢出:隱藏的div

回答

10

如果您知道圖像的寬度和高度事先(即它們都是一樣的),那麼你可以使用舊margin/position招:

#myImage { 
    height: the image's height; 
    left: 50%; 
    margin-left: -half the image's width; 
    margin-top: -half the image's height; 
    position: relative; 
    top: 50%; 
    width: the image's width; 
}
0

說myImg.jpg是100x100px:

<div style="overflow:hidden; width:100%;"> 
    <img src="myImg.jpg" style="left: 50%; top:50%; position:relative; margin:-50px 0 0 -50px; width:100px; height:100px;" /> 
</div> 
1

CSS:

div {background:salmon; width:100%; height:200px; overflow:hidden;} 
img {left: 50%; margin-left:-1500px; position:relative;} 

HTML:

<div><img src="" /></div> 

Demo