LoginSignup
8
4

More than 1 year has passed since last update.

【CSS】position: absoluteの中央寄せ方法まとめ

Last updated at Posted at 2022-09-25

position: absoluteを適用した要素を、上下左右それぞれの中央寄せにする方法をまとめました。

marginを使用する

上下左右中央

{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}

See the Pen abusolute-center1_margin by ushi_osushi (@ushi_osushi) on CodePen.

上下中央

{
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto 0;
}

See the Pen abusolute-center2_margin by ushi_osushi (@ushi_osushi) on CodePen.

左右中央

{
  position: absolute;
  right: 0;
  left: 0;
  margin: 0 auto;
}

See the Pen abusolute-center3_margin by ushi_osushi (@ushi_osushi) on CodePen.

Tips

insetを使用して一括指定する

上下左右中央寄せにするときに、毎回各方向を記述していると面倒ですし行数も増えてしまいます。
insetを使用することで、top, right, bottom, leftmarginなどのショートハンドと同じようにまとめて書くことができます。

{
  inset: 0; /* top:0 right:0 bottom:0 left:0 */
  inset: 0 1; /* top:0 right:1 bottom:0 left:1 */
  inset: 0 1 2; /* top:0 right:1 bottom:2 left:1 */
  inset: 0 1 2 3; /* top:0 right:1 bottom:2 left:3 */
}

中央から少しずらしたい時

中央から右に100pxずらす
{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 100px;
  margin: auto;
}

See the Pen Untitled by ushi_osushi (@ushi_osushi) on CodePen.

transformを使用する

上下左右中央

{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

See the Pen absolute-center_transform by ushi_osushi (@ushi_osushi) on CodePen.

上下中央

{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

See the Pen absolute-center_transform2 by ushi_osushi (@ushi_osushi) on CodePen.

左右中央

{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

See the Pen absolute-center_transform3 by ushi_osushi (@ushi_osushi) on CodePen.

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4