2016-01-13 23 views
1

我想將此響應div居中置於頁面中央(始終垂直居中),高度設置爲auto(頁面呈現或加載時的高度)創建一個始終垂直居中的div

我讀過關於創建一個幽靈元素,然後將其定位對它? 我不確定如何去做這件事,如果有人能指導我,那將是非常棒的!

在此先感謝!

HTML

<div class="container"> 
    <div class="responsive"></div> 
</div> 

CSS

.responsive { 
    width: 50%; 
    height: 200px; 
    margin-left: 25%; 
    background: #25BF59; 
} 

http://jsfiddle.net/qSvAQ/55/

回答

2

試試這個

.responsive { 
 
    width: 50%; 
 
    height: 200px; 
 
    margin-left: 25%; 
 
    background: #25BF59; 
 
    position: absolute; 
 
    top: 50%; 
 
    transform: translateY(-50%); 
 
}
<div class="container"> 
 
    <div class="responsive"></div> 
 
</div>

+0

工程就像一個魅力!謝謝! – Jack

+0

P.S如果你不介意我也問這個問題,你有關於如何使div模糊/冷漠的想法嗎? http://jsfiddle.net/jackcode/qSvAQ/59/ – Jack

+0

你想模糊綠色的div? –

0

你可以使用CSS flexbox,這將工作,而不會對.responsive DIV設置任何寬度

.container { 
 
    height:1000px; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 
.responsive { 
 
    width: 50%; 
 
    height: 200px; 
 
    background: #25BF59; 
 
}
<div class="container"> 
 
    <div class="responsive"></div> 
 
</div>

+0

不工作,因爲我想高度自動(根據設備的高度):/找到上面的解決方案感謝您的幫助! – Jack

+0

這將適用於任何內容。響應的div ??刪除所有高度並添加內容。它會工作嗎? – Aaron

+0

@Jack flexbox與相對內容一起工作。 – Aaron

0

我用雷納德經常描述的技術。另一種方法,如果你用無禮的話,你就不會去砸動畫入禁區是:

$width: 2em; 
$height: 2em; 

.container { 
    position: relative; 
    width: 500px; // some width; 
    height: 500px; // some height; 
} 

.responsive { 
    position: absolute; 
    top: calc(50% - #{0.5*$height}); 
    left: calc(50% - #{0.5*$width}); 
    width: $width; 
    height: $height; 
}