2016-08-28 40 views
0

我正在使用此代碼來顯示採用瀏覽器的完整垂直高度的背景圖像。橫跨所有屏幕分辨率的背景圖像中間的中心div

<div id="outer"></div> 

CSS

#outer { 
    background-image: url(https://www.mydomain./image.jpg); 
    height: 100vh; 
    background-size: cover; 
    background-repeat: no-repeat; 
} 

我期待放置一個DIV中,這是在圖像中所有的屏幕分辨率,中間垂直和水平居中。

到目前爲止,我一直沒有成功,我嘗試了一切。這需要大多數瀏覽器的支持。

+1

請告訴我們你的企圖。 – jedifans

+0

見http://stackoverflow.com/questions/37485593/css-center-any-image-in-div/37485686#37485686 –

+0

請參閱http://stackoverflow.com/questions/19026884/flexbox-center-horizo​​ntally-and -vertically – Dario

回答

1

設置爲在heightwidth內部div,然後用margin: auto水平居中,padding: calc(50vh - 10px) 0垂直居中。 10px必須是你內心的高度的一半div。試試這個:

#outer { 
 
    background-image: url('http://placehold.it/100x100'); 
 
    height: 100vh; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
} 
 
#inner { 
 
    color: red; 
 
    width: 100px; 
 
    height: 20px; 
 
    margin: auto; 
 
    text-align: center; 
 
    padding: calc(50vh - 10px) 0; 
 
}
<div id="outer"> 
 
    <div id="inner">test</div> 
 
</div>

+0

這是最簡單和最值得注意的解決方案。謝謝 ! –

0

選項1:絕對位置和所述翻譯-50%方法

body { 
 
    margin: 0; padding: 0; 
 
} 
 
.outer { 
 
    position: relative; 
 
    background-image:url(http://i.imgur.com/55PnNyJ.jpg); 
 
    height:100vh; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
} 
 
.centered { 
 
    position: absolute; 
 
    top: 50%; left: 50%; 
 
    transform: translateY(-50%) translateX(-50%); 
 
    display: inline-block; 
 
    color: hsla(0, 0%, 100%, 0.4); 
 
    background-color: hsla(0, 0%, 0%, 0.4); 
 
}
<div class="outer"> 
 
    <div class="centered">I'm (almost) On A Boat</div> 
 
</div>

撥弄

https://jsfiddle.net/Hastig/j7rgjspt/2/


選項2:Flexbox的和證明內容/ ALIGN-項目中心

body { 
 
    margin: 0; padding: 0; 
 
} 
 
.outer { 
 
    display: flex; 
 
    justify-content: center; 
 
    align-items: center; 
 
    background-image:url(http://i.imgur.com/55PnNyJ.jpg); 
 
    height:100vh; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
} 
 
.centered { 
 
    display: inline-flex; 
 
    text-align: center; 
 
    color: hsla(0, 0%, 100%, 0.4); 
 
    background-color: hsla(0, 0%, 0%, 0.4); 
 
}
<div class="outer"> 
 
    <div class="centered">I'm (almost) On A Boat</div> 
 
</div>

小提琴

https://jsfiddle.net/Hastig/j7rgjspt/1/