2010-12-16 22 views
32

画面ビューの中央に絶対位置を持つdiv(スクロールまたはスクロールしない)を配置します。画面ビューの中央に絶対divを配置します

私はこれを持っていますが、ドキュメントの半分の場所に現在のビューの中間ではありません。 position: fixed

#main { 
    width: 140px; 
    height:100px; 
    border: 1px solid Black; 
    text-align: left; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin-left:-70px; 
    margin-top:-50px; 
} 

答えて

39

変更position:absolute、あなたが行ってもいいはずです!

position-absoluteと言うとき、参照divは位置相対を持つ親divです。しかし、position -fixedと言うと、参照はブラウザのウィンドウです。それはあなたが望むワットです。 IE6の場合

私はあなたがここに、CSSのcalc()は今、すべてのブラウザでサポートされているので、CSSの表現

+1

IE6とモバイルブラウザを除きます。 – mercator

+0

それはすべてのブラウザで動作する必要があります、javascriptのソリューションが受け入れられます – asker

+1

あなたはあまりにも多くのことを考える必要はありません...それは長い時間のために死んだと考えられています – Kasturi

-3
margin-left: -half_of_the_div; 
left: 50%; 
position: fixed; 

example on codepen

+1

あなたが与えた答えはすでに質問者の質問の一部です。それを確認してください。 – otherDewi

8

を使用するようにcalc()を使用してソリューションを持っていると思います。

#main { 
    width: 140px; 
    height:100px; 
    border: 1px solid Black; 
    text-align: left; 
    position: absolute; 
    top: calc(50vh - (/* height */100px/2)); 
    left: calc(50vw - (/* width */140px/2)); 
} 
+0

これを認識しておらず、私はこのケースに必要なものだった - すばらしい提案@Robert Hahn。 – kyleturner

18

次のCSSを使用します。

.centered { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    /* bring your own prefixes */ 
    transform: translate(-50%, -50%); 
} 
+0

これまでの最もエレガントなソリューションは、すべてのサイズと比率のすべてのボックスで動作し、カスタマイズは必要ありません。クロスブラウザと互換性がありますか? – Gautam

+0

これは、要素のサイズとその内容に大きな影響を与えます。たとえば左にない場合:要素の50%が必要な幅のスペースを占めるが、左の場合は50%となる。サイズが魔法のようになり、内容が複数の行に分割される。 – momomo

0

少し複雑な方法は、複数の外箱を使用することです。この方法は、中央のボックス(背景色がちょうど各ボックスが何をするかを示すために追加された)のハードコーディングされた幅/高さの有無にかかわらずうまく動作します:あなたがしたい場合

/* content of this box will be centered horizontally */ 
 
.boxH 
 
{ 
 
    background-color: rgba(0, 127, 255, 0.2); 
 
    width: 100%; 
 
    height: 100%; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
} 
 

 
/* content of this box will be centered vertically */ 
 
.boxV 
 
{ 
 
    background-color: rgba(255, 0, 0, 0.2); 
 
    height: 100%; 
 
    display: flex; 
 
    flex-direction: row; 
 
    align-items: center; 
 
} 
 

 
/* content of this box will be centered horizontally and vertically */ 
 
.boxM 
 
{ 
 
    background-color: lightblue; 
 
    padding: 3em; 
 
}
<div> 
 
    some text in the background 
 
</div> 
 
<div class="boxH"> 
 
    <div class="boxV"> 
 
    <div class="boxM"> 
 
     this div is in the middle 
 
    </div> 
 
    </div> 
 
</div>

https://jsfiddle.net/vanowm/7cj1775e/

スクロール位置に関係なくdivを表示してからpositionfixedに変更します。

関連する問題