text-align:centerを指定したにもかかわらず、Div枠が中央に配置されない - CSS

text-align:centerを指定したにもかかわらず、div枠が中央に配置されない現象の紹介です。

現象

text-align:centerを指定したにもかかわらず、div枠が中央に配置されません。

不具合の発生するコード

div-center.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="stylesheet" href="div-center.css" />
	<meta charset="utf-8" />
</head>
<body>
  <div class="CenterFrame">
    <p>DIV枠です。</p>
  </div>
</body>
</html>
div-center.css
.CenterOuterFrame {
  text-align:center;
  background-color:#b9d1f6;
  border:solid 1px #2b4eae;
}

表示結果

上記のHTMLファイルをWebブラウザで表示すると下図の結果となります。text-aligh:center を設定していますが、 DIV枠の内部の文字列は中央揃えになっていますが、DIV枠自体は、左寄せで表示されます。

不具合の発生するコード2

DIV枠が左寄せになってしまっているため、さらに外側をDIV枠で囲み、text-aligh:centerを指定すれば、DIV枠が中央揃えになると想定して試してみます。
div-center.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="stylesheet" href="div-center.css" />
	<meta charset="utf-8" />
</head>
<body>
  <div class="CenterOuterFrame">
    <div class="CenterFrame">
      <p>DIV枠です。</p>
    </div>
  </div>

</body>
</html>
div-center.css
.CenterFrame{
  text-align:center;
  width:480px;
  background-color:#efe39c;
  border:solid 1px #ff6a00;
}

.CenterOuterFrame {
  text-align:center;
  background-color:#b9d1f6;
  border:solid 1px #2b4eae;
}

表示結果

表示結果は下図となります。外側をDIV枠で囲み、text-aligh:center を指定しても、内部のDIV枠は左寄せのままです。

対策

スタイルのmarginプロパティをautoに設定すと解決できます。

対策後のコード1

スタイルシートのスタイルで、margin-left:auto; margin-right:auto; を指定します。
div-center.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="stylesheet" href="div-center.css" />
	<meta charset="utf-8" />
</head>
<body>
  <div class="CenterFrame">
    <p>DIV枠です。</p>
  </div>
</body>
</html>
div-center.css
.CenterFrame{
  text-align:center;
  width:480px;
  background-color:#efe39c;
  border:solid 1px #ff6a00;
  margin-left:auto;
  margin-right:auto;
}

表示結果

上記のHTMLをWebブラウザで表示します。DIV枠内の文字列も、DIV枠自体も中央揃えで表示されます。

対策後のコード2

外側をDIV枠で囲んだ場合のコードです。
div-center.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="stylesheet" href="div-center.css" />
	<meta charset="utf-8" />
</head>
<body>
  <div class="CenterOuterFrame">
    <div class="CenterFrame">
      <p>DIV枠です。</p>
    </div>
  </div>
</body>
</html>
div-center.css
.CenterFrame{
  text-align:center;
  width:480px;
  background-color:#efe39c;
  border:solid 1px #ff6a00;
  margin-left:auto;
  margin-right:auto;
}

.CenterOuterFrame {
  text-align:center;
  background-color:#b9d1f6;
  border:solid 1px #2b4eae;
}

表示結果

上記のHTMLをWebブラウザで表示します。外側をDIV枠で囲んだ場合でも、DIV枠は中央揃えで表示されます。


著者
iPentecのメインデザイナー
Webページ、Webクリエイティブのデザインを担当。PhotoshopやIllustratorの作業もする。
掲載日: 2009-10-16
iPentec all rights reserverd.