CSSにおける margin-top と margin-bottom はどちらをつけるべきか
By kkoudev
margin-top と margin-bottom はどちらか一方に寄せて使う方がスタイリング時にわかりやすくなると言われており、
マークアップをする人たちの中ではよくこのどちらをつけるかという話で盛り上がることがあります。
CSS TrickがTwitterでアンケートを取った結果では margin-bottom 派の方が61% と margin-top 派よりも多かったようですが、
実際は恐らくそこまで差はないのではないかと思います。
今回は margin-top をつけるケースと、margin-bottom をつけるケースの各々の利点や欠点についてピックアップしていきたいと思います。
margin-top に寄せる理由
margin-top 派の方が何故 margin-top を使うのかというと、
その最たる理由は隣接兄弟結合子(例: .aaa + .aaa)を使うためにあると考えられます。
隣接兄弟結合子は後続の要素に対してのセレクタとなるため、縦配置される要素の場合は margin-top を使わざるを得ません。
隣接兄弟結合子は横一列や縦一列に並んだ要素のマージンを指定する際には非常に扱いやすく、
:first-child または :last-childの擬似クラスをつかう場合とは異なり、先頭または末尾のマージンの打ち消しも不要になります。
また、LPのようなページ数が少なく、パーツ化をあまり意識しなくても良い変更の少ないサイトをコーディングする際は、
コーディングのしやすさからいうと下に配置する要素に margin-top をつけてマージン調整していく方が作りやすくはなります。
もっとも慣れの問題だとは思いますが、LPをよくマークアップする人ならこの感覚はなんとなく理解いただけるかと思います。
margin-bottom に寄せる理由
一方で、margin-top はAtomic Designにおける Templates または Pages におけるパーツ化の考え方から見ると欠点があります。
例えばサイトの見出しを例にすると、種類の違いはいくつかあれどそれらの同種類の中で見出しの下のマージンはどのページでも統一したくなるかと思います。
その際、各ページごとに同じマージンを margin-top で付与していくと、下にくる要素がページごとにバラバラであるため、
各ページの見出しの次に来る要素に同じ margin-top を付与する必要が出てくるかと思います。
これはつまり、修正が発生したときにも各ページごとに修正が必要になり、ページ数が多ければ多いほど大変なことになります。
(変数を使っていればもちろん問題はありませんが、マージンだけのために変数を都度定義するというのも冗長ではあります)
代わりに、見出しパーツに margin-bottom をつけると後続要素に何がきても同じマージンをつけられるばかりか、修正も少なく済みます。
恐らくmargin-bottom派が好んで margin-bottom を使うのはこの見出しとマージンの考え方を重要視しているためになると考えられます。
上から下に要素を配置する際に上の要素がマージンを知っておくと、パーツ化する際に修正が少なく済むケースが多い、というわけです。
またこの考え方は、例えばサイトの修正で要素の配置位置(順番)が変わることがあったとき、
margin-top を使っていると配置位置が変わるとほぼ必ず修正する必要が出てきます。
これは見出しとマージンの例からもわかるとおり、本来マージンは後続要素ではなく、見出しそのものが適切なマージンを知っておくべきだからです。
要するに margin-bottom を使っているとそのような要素の位置変更時においても修正が少なく済むケースが多いという理由になります。
結局どちらがいいのかはCSS設計や何を重要視するかによる
とはいえ、自分としてはCSS設計次第では正直どちらでもありだとは思います。
自分がマークアップする際のCSS設計としてはAtomic Designを採用しているのですが、
Atoms、Molecules、Organismsにおいてはコンポーネントの最上位コンテナにはマージンを付与しません。
これはAtomic Designのルールとしても有名かと思うのですが、そうなると各コンポーネントの最上位コンテナのマージンの付与は Templates または Pages の仕事になります。
その場合、結局のところマージンの付与は柔軟性を持たせて最上位となるPagesで各パーツをを div で囲んで付与することが多くなります。
何故なら共通パーツ化を行うことで今後の変更のしやすさを保証するというよりは、
デザインの変更が発生したときの影響範囲を各ページに留めておくことで修正の影響を小さく収めたいという側面の方が、結果的に保守性に強い設計となることがCSSにおいては多いからです。
共通化には必ずこの2点のジレンマが存在するので、一概にパーツ化と修正の小ささだけでは評価しづらい面がCSSにおいては存在します。
となると、どちらを採用したからといって大きく問題になるケースはないと考えています。
ただ、ページ内の配置順番の変更におけるマージンの付け替えの少なさについては margin-bottom に分があると考えているので、
強いていうなら自分は margin-bottom を使うというところなのですが、
これはケースにもよると思うのと細かい問題な気もするので、ここまでくるとあとは好みの問題な気もしています。
まとめ
margin-top にも margin-bottom のどちらにも利点と欠点があることがわかったかと思います。
なので自分の場合はどちらか一方に強制的に寄せることには拘らず、
margin-bottom を基本としつつ例外的に margin-top も使うようにしています。
具体的にいうと、「基本は margin-bottom とするが、隣接兄弟結合子を使う場合のみ margin-top を許可する」としています。
CSS Selectors Level 4の :has 擬似クラスがブラウザに実装されれば隣接兄弟結合子も使う必要がなくなるのですが、
現状どのブラウザも実装していないところを見るとしばらくはこの状態が続くかと思われます。
ただどちらか一方に統一しなければルールとして曖昧になりやすいので、その点はレビューなどで担保するしか現状はなさそうです。