margin: 0 auto;で中央寄せができない?
前回の記事で書いたhtmlの中央寄せだが、実はちょっとハマった部分がある。
最初、mainというクラスを定義した<div class=”main”>~</div>タグに対してcssで.main {margin: 0 auto;}で中央寄せしようとしていて「テキストやボタンに中央寄せが効かない」と悩んでいたのだが、私が作成したhtmlだと「text-align: center;」を使わないと所望の中央寄せができなかった。
文章で書くより実際の表示を見た方が早いと思うので、以下のページに画像と共に備忘録をメモしておく。
margin: 0 auto;はブロック要素、 text-align: center;はインライン要素に反映
両者の違いは、ずばりmargin: 0 auto;はブロック要素、 text-align: center;はインライン要素に対して反映されるという点である。文章で書いてもわかりづらいと思うので、実際にcssでmargin: o auto;した結果とtext-align: center;した結果を比べてみる。対象のhtmlは前回の記事に書いた以下のもの。
<!DOCTYPE html> | |
<html> | |
<head> | |
<link rel = "stylesheet" href = "omikuji_element_center.css"/> | |
<script> | |
function tryFortune() { | |
var resultInt = Math.floor(Math.random () * 7) | |
switch (resultInt) { | |
case 0 : resultText = "大凶"; resultClass = "bad"; break; | |
case 1 : resultText = "凶"; resultClass = "bad"; break; | |
case 2 : resultText = "末吉"; resultClass = "normal"; break; | |
case 3 : resultText = "小吉"; resultClass = "normal"; break; | |
case 4 : resultText = "中吉"; resultClass = "good"; break; | |
case 5 : resultText = "吉"; resultClass = "good"; break; | |
default : resultText = "大吉"; resultClass = "good"; break; | |
} | |
document.getElementById("result").textContent = resultText; | |
document.getElementById("result").className = resultClass; | |
console.log(resultClass); | |
} | |
</script> | |
</head> | |
<body> | |
<div class="main"> | |
<h1>HTMLとJavaScriptによるWebおみくじ</h1> | |
<button class = "button_omikuji" onclick="tryFortune()">おみくじを引く</button> | |
<p id = "result"></p> | |
</div> | |
</body> | |
</html> |
これに対して、<div class=”main”>タグで定義したブロック要素にmargin: o auto;を追加したcssファイルと、text-align: center;を追加したcssファイルの2通りを用意して、それぞれの実行結果を比較してみる。なお、違いが分かりやすいように<div class=”main”>タグのブロック全体に黄色い色を付けている。
margin: 0 auto;を使った場合
まずはmargin: o auto;を追加したcssファイル↓
* { | |
font-size:20px; | |
} | |
h1 { | |
font-size:22px; | |
margin:20px; | |
} | |
.main { | |
margin: 0 auto; | |
background-color: yellow; | |
} | |
.bad{ | |
color:red; | |
} | |
.normal{ | |
color:green; | |
} | |
.good{ | |
color:blue | |
} |
こちらを適応したhtmlの表示結果が以下の画像。
<div class=”main”>タグで定義した黄色のブロック要素は幅を指定していないため、ブラウザ一杯に横幅が取られている。そのため、ブロック要素を中央寄せしても、ブロック要素の位置は変わらない。
また、margin: 0 auto;はブロック要素を中央寄せするものなので、ブロック要素内に書かれた文章やボタンなどのインライン要素は中央に寄らない。
text-align: center;を使った場合
次にtext-align: center;を追加したcssファイル↓
* { | |
font-size:20px; | |
} | |
h1 { | |
font-size:22px; | |
margin:20px; | |
} | |
.main { | |
text-align:center; | |
background-color: yellow; | |
} | |
.bad{ | |
color:red; | |
} | |
.normal{ | |
color:green; | |
} | |
.good{ | |
color:blue | |
} |
こちらを適応したhtmlの表示結果が以下の画像。
text-align: center;はインライン要素に効くため、黄色いブロック要素の中のテキストやボタンが中央寄せされている。
今回少しハマってしまったが、ブロック要素とインライン要素について理解することができたからまぁ良しとする。
勉強記まとめ
今までの勉強記は以下にまとめています。初学者の目線で色々つくったり、試してみたりしてるので、興味があればどうぞ。