【HTML&CSS】インラインレベル要素ブロックレベル要素


今回はインライン要素とブロック要素について見ていきましょう
ブロック要素
displayプロパティの初期値がblock。
ブロック要素には<h1><h2>などの見出しや<p>段落、<div><ol><ul>などがあります。
ブロック要素の特徴
要素が横いっぱいに広がる
ブロック要素はこのように横幅いっぱいに広がります。
改行されて縦並びになっていく。

余白が入る場合がある
ブロック要素は初期値で余白が入る場合があります。

検証ツールで見るとこのようにmarginが初めから設定されています。

余白を入れたくないときはこのように『margin-top』と『margin-bottom』を0にすると余白がなくなります。
h1 {
background-color:darkolivegreen;
margin-top: 0;
margin-bottom: 0;
}
h2 {
background-color: olive;
margin-top: 0;
margin-bottom: 0;
}

幅と高さの指定ができる
ブロック要素は幅と高さの指定ができます。
h1 {
background-color:darkolivegreen;
width: 300px;
height: 300px;
}
h2 {
background-color: olive;
width: 200px;
height: 200px;
}
h3 {
background-color:darkcyan;
width: 100px;
height: 100px;
}
h4 {
background-color:darkgoldenrod;
width: 50px;
height: 50px;
}

他のブロック要素やインライン要素を配置することができる
ブロック要素<div>の中にブロック要素<p>を入れると改行される。
ブロック要素<p>にインライン要素<strong>を入れても改行しない。

インライン要素
displayプロパティの初期値が『inline』
<strong><a><br><img><small>など
インライン要素の特徴
改行が入らない
改行が入らないでこのように横に並んでいきます。

画像も横並びになります。

幅と高さが指定できない
幅と高さを指定しても変わらない。
strong {
background-color: darkgray;
width: 50px;
height: 50px;
}
span {
background-color: darkgoldenrod;
width: 50px;
height: 50px;
}
a {
background-color: peru;
width: 50px;
height: 50px;
}

インライン要素で幅と高さを指定したい場合
displayプロパティを『inline-block』にする
strong {
background-color: darkgray;
display: inline-block;
width: 100px;
height: 100px;
}
span {
background-color: darkgoldenrod;
display: inline-block;
width: 100px;
height: 100px;
}
幅と高さが指定できました。

<img>タグはインライン要素ですが幅と高さは指定することができます。
まとめ
CSSでの配置につまずきがちなインライン要素とブロック要素ですがそれぞれの特徴をよく理解することが大事かなと思います。