0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSSのボックスモデルについて

Posted at

テキストボックスはCSSでコンテンツの表示領域を調整する基本的なボックスモデルを扱います。本記事では、初心者が理解しやすいように基本プロパティと実例を交えて解説します。

1. width(幅の設定)

width はコンテンツの幅を設定するプロパティです。
デフォルトでは、親要素やブラウザの幅に基づいてサイズが決まります。

基本的な書き方

h1 {
    width: 200px; /* 幅を200pxに設定 */
}

2. Height(高さの設定)

height はコンテンツの高さを指定するプロパティです。
初期値はコンテンツのサイズに合わせて自動調整されます。

基本的な書き方
h1 {
    height: 100px; /* 高さを100pxに設定 */
}

3. margin(外側の余白)

margin は要素の外側に余白をつけるプロパティです。
また負の要素、値にautoを扱えます
• 負の値: 要素を引き寄せる。
• auto: 要素を親要素の中央に配置する(特に横方向)。

基本的な書き方
h1 {
    margin: 20px auto; /* 上下20px、左右中央寄せ */
}

マージンの相殺

上下のマージンは相殺されます。
(例: 親の margin-bottom と子の margin-top が重なる場合。隣り合う要素同士のmarginがかぶる場合)
左右のマージンやパディング、ボーダーがある場合 は相殺されません。

4.text-align(テキストの中央揃え)

text-align は、ボックス内のテキストやインライン要素を水平中央に配置するプロパティです。

基本的な書き方
h1 {
    text-align: center; /* テキストを中央揃え */
}

5. box-sizing(ボックスモデルの制御)

box-sizing は、要素のサイズにパディングやボーダーを含めるかどうかを制御します。
• content-box(デフォルト): パディング・ボーダーは含まない。
• border-box: パディング・ボーダーを含める。

基本的な書き方
/* パディングとボーダーを含める設定 */
h1 {
    box-sizing: border-box;
}
div {
    width: 200px;
    padding: 20px;
    border: 5px solid black;
    box-sizing: border-box;
}

結果の違い

設定 2
content-box width + padding + border
border-box width

6.マージンとパディングの違い

項目 マージン パディング
位置 要素の外側にある余白 要素の内側にある余白
影響 隣接要素との間隔を調整 ボックス内のコンテンツとの間隔を調整

7.よくある間違いと解決策

  1. テキストがはみ出してしまう
    → box-sizing: border-box; を設定。
  2. 中央揃えがうまくいかない
    → テキストの場合は text-align: center、ボックス全体なら margin: auto。
  3. マージンの相殺に困る
    → 親要素に padding や border を設定して解消。

まとめ

width と height: コンテンツの幅や高さを制御。
margin と padding: 要素の外側・内側の余白を調整。
box-sizing: ボックスの計算方法を制御。
中央揃え: テキストは text-align、ボックス全体は margin: auto。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?