2014-01-19 14 views
1

我正在使用一組HTML模板,它使事情變得有點棘手,以完全按照自己的方式進行自定義。所以我堅持一種缺乏靈活性的結構。當它被限制在偏離中心的限制寬度div時,在頁面上水平居中div

我有一個佔用頁面寬度50%的div,但是我想在頁面中間放置一個包含div的div。由於頁面其他部分的其他限制,我確實無法將父div設置爲position:relative

這是我後的效果: enter image description here

這是我迄今(沒有工作)代碼:

HTML:

<div class="parent"> 
    <div class="centerpage"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Berlin_U-Bahn_Train_A3L71.jpg/220px-Berlin_U-Bahn_Train_A3L71.jpg"></div> 
</div> 

CSS:

.parent { 
    background-color: #85D782; 
    height: 400px; 
    width: 50%; 
    position: relative; 
} 

.centerpage { 
    position: absolute; 
} 
+0

你有沒有嘗試'.centerpage {position:relative;保證金:0汽車; }'? –

+0

@JaceCotton會將它置於父級中,而不是預期的效果。我不明白預期的效果 - 火車圖像的大小如何決定?它的定位是什麼?它是固定大小嗎? –

+2

我們需要更多的上下文。也許一個jsfiddle或它的鏈接生活? –

回答

1

可以使用的絕對和負利潤率的老方法: http://codepen.io/anon/pen/Htpen

.parent { 
    background-color: #85D782; 
    height: 400px; 
    width: 50%; 
    position:relative; 
} 
.centerpage { 
    position: absolute; 
    left:100%; 
    top:50%; 
    vertical-align:middle; 
    margin :-80px 0 0 -110px;/* negative margin is equal to half height/width of image */ 
} 

或使用背景圖像或梯度http://codepen.io/anon/pen/GDbtg

.centerpage { 
    background: 
    linear-gradient(to right, 
    #85D782 0%, 
    #85D782 50%, 
    #ffffff 50%, 
     #ffffff 
) 
    ; 
    height: 400px; 
text-align:center; 
    line-height:400px; 
} 
img{ 
    display:inline-block; 
    vertical-align:middle; 
} 
+0

我添加使用codepen,無法編輯你的小提琴,我的屏幕太小...真的不友好我這個小提琴:) –

1
put image into a div and apply class below 

{ 
width: 100px /* with your width whatever it is */; 
text-align: center; 
padding: 0px; 
height: 110px; 
display: table-cell; 
vertical-align: middle; 
} 

and add one more class 
.centerpage img { 
width:100%; 
}