2013-12-08 103 views
0

如果我要用flexbox在屏幕中間放置一個元素,這個代碼最優雅嗎?Flexbox:屏幕中間的居中元素

http://codepen.io/vennsoh/pen/wEAmz

HTML

<div class='btn'></div> 

CSS

body{ 
    overflow: hidden; 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    display: flex; 
} 

.btn{ 
    width: 10rem; 
    height: 10rem; 
    background-color: #033649; 
    margin: auto; 
} 

看來,我必須使用的位置是:絕對的身高和體重+ 100%,實現這一目標。

回答

8

您必須使用position:absolute,因爲元素的默認值是position:relative,並且在這種情況下,沒有什麼可相對的,因爲您已將flex容器作爲主體。

您的代碼將正常工作,但到中央的命令對象,在實際的柔性模型本身就像這樣:

body{ 
    overflow: hidden; 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    display: flex; 
    justify-content: center; /*centers items on the line (the x-axis by default)*/ 
    align-items: center; /*centers items on the cross-axis (y by default)*/ 
} 

如果你這樣做,你可以刪除保證金:從您的.btn一流汽車也許在你的代碼中給出更多的擺動空間。

Here是flexbox所有東西的好資源。

+0

感謝您的回覆。 – Vennsoh