2014-02-07 207 views
1

我試圖用線高來垂直居中div,而未指定線高的設置像素值。我需要將line-height擴展爲div的大小。使用'100vh'的作品,但視口單元廣泛支持不夠廣泛。將行高設置爲100%似乎不起作用。這裏是我的HTML:線高與未指定高度的div的垂直對齊

<div class="background"> 

<div class="lightboxbg"> 
    <div class="wrapper"> 
    <div class="centerme"></div> 
    </div> 
</div> 

</div> 

我的CSS:

html, body { 
    width: 100%; 
    height: 100%; 
    padding: 0px; 
    margin: 0px; 
} 

.background { 
    width: 90%; 
    height: 100%; 
    background-color: AntiqueWhite; 
} 

.lightboxbg { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    background-color: black; 
    vertical-align: middle; 
    text-align: center; 
} 

.wrapper { 
    vertical-align: middle; 
    line-height: 100%; 
    height: 100%; 
    width: 100% 
} 

.centerme { 
    vertical-align: middle; 
    display: inline-block; 
    width: 100px; 
    height: 100px; 
    background-color: blue; 
} 

And here's a jsfiddle.如果我能得到的包裝的行高擴展到包裝的高度藍盒子將被集中,但我不不知道該怎麼做。謝謝閱讀。

編輯:查看Nathan Lee的表格單元格的解答,Fredric Fohlin的一個非常狂野的'絕對定位'答案和MM Tac的解決方案使用絕對定位的答案。

回答

1

看看這個想法。它可能適合你:http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/

.Center-Container { 
    position: relative; 
} 

.Absolute-Center { 
    width: 50%; 
    height: 50%; 
    overflow: auto; 
    margin: auto; 
    position: absolute; 
    top: 0; left: 0; bottom: 0; right: 0; 
} 

在你的情況下,包裝所需要的相對定位,以及「我爲中心」的絕對定位。

+0

這很酷,我還沒有得到它在我目前的小提琴工作,但我仍然在玩。 – Ber

+0

好吧,我讀過你的其他評論,我想我需要清楚「中心我」元素需要設置高度。如果該元素沒有高度,則會獲得與父元素相同的高度。 –

1

與下面的CSS替換.centerme

CSS:

.centerme { 
    width: 100px; 
    height: 100px; 
    background-color: blue; 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    margin-left: -50px; /* negative-half of element's width*/ 
    margin-top: -50px; /* negative-half of element's height*/ 
} 

這裏是一個DEMO,這裏是一個整版RESULT

UPDATE

要可變長度中心格簡單,只是刪除heightwidthmargin-left,從.centerme CSS margin-top參考。

.centerme { 
    background-color: blue; 
    position: absolute; 
    left: 50%; 
    top: 50%; 
} 

這是UPDATED DEMO

+0

這是一個有用的解決方案,不幸的是我的centerme對象將有一個可變的高度和寬度,我只用了100px作爲例子。不過,它可以用jQuery來完成。 – Ber

+0

很簡單,看我更新的答案。 –

+0

阿酷,沒想到那個。唯一的事情是,它垂直完美地居中,但橫向關閉,因爲它從距離開始時的50%處開始測量。感謝您的幫助。 – Ber

3

在這裏,你去。

WORKING DEMO

CSS的變化:

.lightboxbg { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    background-color: black; 
    vertical-align: middle; 
    text-align: center; 
    display: table; 
} 

.wrapper { 
    vertical-align: middle; 
    line-height: 100%; 
    height: 100%; 
    width: 100%; 
    display: table-cell; 
} 

希望這有助於。

+1

甜,這看起來很簡單,絕對有幫助。 – Ber

+0

謝謝@Ber :) – Nitesh