<div class="outer"> <div class="inner"> ほげほげほげほげ <br> ふがふが </div> </div>
absolute + negative margin
メリット
.outerのサイズは可変
挙動がわかりやすい
検索したとき出てくる率が高い
デメリット
.innerのwidthとheightが固定される
marginの値がwidthとheightの値に依存する
.outer {
position: relative; /* or absolute, fixed */
}
.inner {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; /* width / 2 */
margin-top: -100px; /* height / 2 */
}
absolute + transform
.outer, .inner共にサイズは可変
簡潔でわかりやすい
デメリット
transform対応ブラウザのみ
Safari8, IE9, Android4.4以前ではプレフィックスが必要
JSで単純に.innerのoffsetTop, offsetLeftを取得しても
top: 50%; left: 50%; の位置の値しかとれない
(transformの値は別で計算が必要。jQueryのoffset()ならOK)
.outer {
position: relative; /* or absolute, fixed */
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
absolute + offsets + margin auto
‘left’、’width’、’right’の3つすべてが’auto’である場合:(省略)
この3つが’auto’でない場合:’margin-left’および’margin-right’の両方が’auto’である場合、2つのマージンが等しい値を得る追加条件の下で式を解き、
left、width、rightがすべてauto以外で、margin-leftとmargin-rightの両方がautoの場合は両側のmarginが同じ幅になる!→コンテンツが中央に配置される!
縦方向についても同様です。
top, right, bottom, leftに0を指定していた理由:
値を初期値のauto以外の何かにする必要があった!
(なので対になる値が等しければ0以外でもOK)
.outerのサイズは可変
widthとheightの値が他のプロパティに影響しない
デメリット
.innerのwidthとheightが固定される
指定しないと.outerいっぱいのサイズになる
top, right, bottom, leftの4つの指定が冗長
.outerが.innerより小さいと負になり中央に寄らない
.outer {
position: relative; /* or absolute, fixed */
}
.inner {
width: 200px;
height: 200px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
table-cell + text-align + vertical-align
.outerのサイズは可変
.innerのサイズも可変
デメリット
必要な要素がひとつ多くなる
.outerの幅を100%にしたい場合、明示的に指定が必要
<div class="outer"> <div class="cell"> <div class="inner">ほげほげほげほげ ふがふが</div> </div> </div>
.outer {
display: table;
}
.cell {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inner {
display: inline-block; /* or width & margin: auto; */
}
flex
メリット
顧客が本当に必要だったもの
デメリット
ブラウザを気にする必要がある
.outer {
display: flex;
justify-content: center;
align-items: center;
}