中央寄せ(HTML/CSS)

前書き

HTMLコーディングに使える、中央寄せに関する小技を掲載しています。

目次

  1. 左右の中央寄せ
  2. 上下左右の中央寄せ

左右の中央寄せ

インライン要素(文字、画像、ボタン等)

インライン


<p><span>インライン</span></p>

p { text-align: center; }

ブロック要素

ブロック

<div class="wrap">
  <div class="box">ブロック</div>
</div>

.box {
  width:6em; /* 必須 */
  margin: 0 auto; /* 左右のマージンをautoにする */
}

上下左右の中央寄せ

flexbox

子要素

<div class="wrap">
  <div class="item">子要素</div>
</div>

.wrap{
  display: flex;
  justify-content: center; /* 左右中央寄せ */
  align-items: center; /* 上下中央寄せ */
  height: 5em;
}

grid

子要素

<div class="wrap">
  <div class="item">子要素</div>
</div>

.wrap{
  display: grid;
  justify-content: center; /* 左右中央寄せ */
  align-content: center; /* 上下中央寄せ */
  height: 5em;
}

absolute と translate

要素

<div class="wrap">
  <div class="item">要素</div>
</div>

.wrap{
  position: relative; /* 基準 */
  height: 5em;
}
.item{
  position: absolute;
  top:50%; /* .wrapの50% */
  left: 50%; /* .wrapの50% */
  transform: translate(-50%,-50%); /* .itemの-50% */
}

absolute と margin

要素

<div class="wrap">
  <div class="item">要素</div>
</div>

.wrap{
  position: relative;
  height: 5em;
}
.item{
  position: absolute;
  top:0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
  width: 4em; /* 必須 */
  height: 2.75em; /* 必須 */
}

table

要素

<table class="wrap">
  <tr>
    <td class="inner"><span class="item">要素</span></td>
  </tr>
</table>

.wrap{
  width: 100%;
  height: 5em;
}
.inner{
  text-align: center; /* 左右中央寄せ */
  vertical-align: middle; /* 上下中央寄せ */
}
.item{
  display: inline-block;
}

関連記事

横並び(HTML/CSS/JS)

先頭に戻る
ページの先頭に戻る