2016-08-28 6 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

内側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:フレキシボックスと正当化コンテンツ/ ALIGN-商品中心ためheightwidthを設定

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/