2016-08-20 6 views
3

htmlにはdisplay: tablebodyにはdisplay: table-cellを使用しています。最近、すべての内容が画面中央に表示されます。これは段落、見出し、入力、ラベルなどで動作しますが(少なくとも私がテストした限り)、div要素では動作しません。
divの要素にこの方法を適用する方法はありますか?純粋なCSSソリューションが最適でしょう。ディスプレイを使用している場合、中央に表示されない:テーブルセル

also on Codepen

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

答えて

4

ちょうどいい仕事.. margin: 0 auto;を追加します。 0自動;:

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
    margin:0 auto; 
 

 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

+0

それは、なぜそれがしかし、そうするんですか? 'margin:0 auto'ルールはそれをどうするのですか? –

+2

'margin:0 auto'を適用したオブジェクトの幅を指定すると、そのオブジェクトはその親コン​​テナ内の中央に座ります。 2番目のパラメータとして 'auto'を指定すると、ブラウザは自動的に左右のマージンを自動的に決定します。左右のマージンを同じサイズに設定します。最初のパラメータ0は、上限と下限の両方が0に設定されることを示します。 –

1

だけマージンを追加.leafクラスへの

html { 
 
    display: table; 
 
    height: 100%; 
 
    width: 100%; 
 
    text-align: center; 
 
} 
 
body { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
} 
 
.hidden { 
 
    display: none; 
 
} 
 
.leaf { 
 
    margin: 0 auto; 
 
    border-radius: 15px 2px 15px 2px; 
 
    border: 1px solid green; 
 
    background-color: green; 
 
    width: 250px; 
 
    height: 80px; 
 
}
<div class="leaf">Why am I not centered?</div> 
 
<p>And why am I centered?</p>

+1

@Angelos、オートトリックの詳細については、こちらをご覧ください[http://stackoverflow.com/questions/3170772/what -does-auto-do-in-margin0-auto) – Divsign

関連する問題