2014-10-17 77 views
0

我需要在頁面上垂直居中未知高度的元素。使用CSS在頁面上垂直居中元素?

我可以垂直居中相對於這個含有格:

.one { 
    background: grey; 
    width: 50%; 
    position: relative; 
    top: 50%; 
transform: translateY(-50%); 
    margin: auto; 
} 
.cont { 
    background: blue; 
    height: 300px; 
} 

http://codepen.io/anon/pen/lfrJx

但是我不能讓它在頁面上垂直居中:

.one { 
    background: grey; 
    width: 50%; 
    position: relative; 
    top: 50%; 
transform: translateY(-50%); 
    margin: auto; 
} 
.cont { 
    background: blue; 
    height: 100%; 
} 

http://codepen.io/anon/pen/gqLcB

+2

[** CSS-Tricks.com - 完整的定心件**](http://css-tricks.com/centering-css-complete-guide /) – 2014-10-17 11:09:25

+0

檢查到此http://codepen.io/anon/pen/ycjsp – 2014-10-17 11:10:15

+0

'html,body {height:100%; }'應該這樣做。 – somethinghere 2014-10-17 11:17:47

回答

1

把這個CSS :)

.one { 
 
    background: grey; 
 
    width: 50%; 
 
    position: relative; 
 
    margin-top:auto; 
 
    margin-bottom:auto; 
 
    vertical-align:middle; 
 
} 
 
.cont { 
 
display: table-cell; 
 
    background: blue; 
 
    width:100%; 
 
}