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?

【フロントエンド1000本ノック】0024_marginの相殺(margin collapsing)が発生するパターンと、それを「ブロックフォーマットコンテキスト(BFC)」を生成して解決する実装を行え。

Posted at

この記事は人間が書きました

はじめに

こんにちは、赤神です!
この記事は、「1000本ノック」という取り組みの中のフロントエンドのための課題の1つです。

「1000本ノックとは」
https://qiita.com/sora_akagami/items/c8da4296dea3823376ca

Margin の相殺とは?

通常、隣り合う要素の margin は足し算されません。上下に隣接するブロック要素の縦方向の marginmargin-topmargin-bottom)が接する場合、大きい方の margin の値が採用され、小さい方は無視されます。これを「相殺」と呼びます。

例えば、上の要素に margin-bottom: 30px 、下の要素に margin-top: 50px を指定した場合、間のスペースは80pxではなく、大きい方の50pxになります。

Margin の相殺が起こる主なパターン

①隣接する兄弟要素の間
②親子要素の間(親要素に borderpadding がない場合、親の margin-top と子の margin-top が相殺する)

ブロックフォーマットコンテキスト(BFC)

BFCが作られた要素(コンテナ)は、以下のような特別なルールを持つようになります。

①マージンの相殺を防ぐ

コンテナの内側にある子要素の margin が、外側にある要素の margin と相殺しなくなります。

②回り込み(float)を解除する

コンテナの内側にある float 指定された要素の高さを、コンテナが正しく認識できるようになります(clearfixと同じ効果)。

BFCを生成する主なCSSプロパティ

意図的にBFCを作り出すには、親要素に以下のいずれかのスタイルを指定します。

  • overflow: hidden;autoscrollでも可)
  • display: flow-root; (BFCを作るためだけに用意された最新の値)
  • display: inline-block;
  • position: absolute;
  • position: fixed;

BFCを意図的に生成することで、マージンの相殺や float の回り込みといった、予期せぬレイアウトの崩れをコントロールすることができます。

作成したコード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>フロントエンド1000本ノック 0024</title>
</head>
<body>
    <main>
      <h1>marginの相殺とBFC</h1>

      <section>
        <h2>問題の再現</h2>
        <div style="width: 150px; height: 100px; background-color: lightblue; margin-top: 50px;">
          <div style="width: 100px; height: 50px; background-color: lightcoral; margin-top: 30px;"></div>
        </div>
      </section>
      

      <section>
        <h2>問題の解決</h2>
        <div style="overflow: hidden; width: 150px; height: 100px; background-color: lightblue; margin-top: 50px;">
          <div style="width: 100px; height: 50px; background-color: lightcoral; margin-top: 30px;"></div>
        </div>
      </section>
    </main>
    <footer>
      <p>Copyright 2025</p>
      <p>フロントエンド1000本ノック</p>
    </footer>

</body>
</html>
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?