🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

position: absoluteな要素をcenter寄せにする

よく使う割にイマイチ思い出せないのがコレ。

`position: absolute`じゃないなら、`margin: 0 auto`とかで良いんですけどねー。
それっぽい帯のデザインを作るときとかでbefore/after擬似要素を使う時はたいてい`position: absolute`なので、うまいこと真ん中に寄ってくれないんですよね・・。

でも、よくよく考えたらそれも大したことはなくて。
縦にも横にもcenterしたい場合のやつ。

サンプル

Html

<div class="wrapper">
  <div class="first">div</div>
  <div class="second">div</div>
</div>

Css

.wrapper {
  background-color: #fff;
  padding:50px;
  margin: 0;
  text-align: center;
}

.first,
.second {  
  height: 20px;
  width: 100%;
  margin: 0 auto 100px;
  background-color: #ccc;
  position: relative;
}

.first::before,
.first::after,
.second::before,
.second::after {
  position: absolute;
  display: block;  
}
  
.first::before {
  background-color: #bbb;
  content: "::before div";
  height: 50px;
  width: 100px;
  left: 0; /* Wherever you go. */
  top: 50%; /* Vertically centered. */
  margin-top: -25px; /* Half of my height. */
}
.first::after {
  background-color: #ddd;
  content: "::after div";
  height: 100px;
  width: 100px;
  right: 0; /* Wherever you go. */
  top: 50%; /* Vertically centered. */
  margin-top: -50px; /* Half of my height. */
}

.second::before {
  background-color: #bbb;
  content: "::before div";
  height: 20px;
  width: 400px;
  top: -20px; /* Wherever you go. */
  left: 50%; /* Horizontally centered. */
  margin-left: -200px; /* Half of my width. */
}
.second::after {
  background-color: #ddd;
  content: "::after div";
  height: 40px;
  width: 100px;
  bottom: -40px; /* Wherever you go. */
  left: 50%; /* Horizontally centered. */
  margin-left: -50px; /* Half of my width. */
}

ポイント

ソース見れば一目瞭然ですが。

  • 縦方向ならtop、横方向ならleftに50%
  • 縦方向なら自身の高さ、横方向なら自身の幅の半分をネガティブマージン

これだけ。

20141212追記

このネガティブマージンの計算が中々に面倒で、最近はこっちを使ってます。

.centerに寄せたい要素 {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

top/bottomの組で上下、left/rightの組で左右真ん中になります。