margin-top派かmargin-bottom派で言えば、margin-top派です
世の中にはmargin-top派とmargin-bottom派がいるとかいないとか。
自分はmargin-top派です。
margin-left派とmargin-right派がいるならば、margin-left派です。
試しにmargin-bottom派になってみようかなと頑張ってみたんですけど、やはり慣れもあり、margin-topの方がしっくりきたのでエントリーを起こすことにしました。
margin-top派な理由
margin-top派になったのには理由はなくて、なんとなくmargin-top派になった気がするのですが、margin-bottom派に移るのが少し面倒な理由はあります。
その理由は:first-child
擬似クラスの存在です。
例1
例えば、以下の様なHTMLがあったとします。各section.content
の間には30px
の余白が欲しかったとします。
<section class="content"> <h1>title1</h1> <p>section2</p> </section> <section class="content"> <h1>title2</h1> <p>section2</p> </section> <section class="content"> <h1>title3</h1> <p>section3</p> </section>
この場合、:first-child
を利用すると、margin-top
で楽にレイアウトできます。
section.content { margin-top: 30px; } section.content:first-child { margin-top: 0; }
margin-top
で、30px
の余白を取ります。そうすると各section.content
の間には、30px
の余白が確保できます。しかし、このままだと、先頭のsection.content
には余計な30px
の余白が入ってしまいますので、:first-child
擬似クラスを利用して、先頭の余白を0
にすることで、各section.content
の間に30px
の余白を作るということが実現できます。
例2
横並びでも同じです。リストが横並びで、各リスト項目の間に20px
の余白を取りたい場合です。
<ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul>
CSSはこんな感じになります。
ul { margin: 0; padding: 0; } ul li { list-style-type: none; display: inline; margin-left: 20px; } ul li:first-child { margin-left: 0; }
こんな感じです。
このケースでは、:first-child
を使わなくても、以下のようにすればOKですね。
ul { margin: 0 0 0 -20px; padding: 0; } ul li { list-style-type: none; display: inline; margin-left: 20px; }
それ、:last-childでできるよ
そうなんですけど、IE7から対応しているのと、IE9から対応しているのとでは、大きな違いがありますし、IE8とか捨てれる状況でないので、:last-child
を実務で使える状況はあまりありません。
まとめ
margin-top派、かつ、margin-left派です。その理由は:first-child
擬似クラスを利用して、余白を調整する機会が多いからです。
IE6に対応しないといけない案件の場合は、:first-child
の代わりに、.first
を付けることがありますが、要素を後ろに追加する機会の方が多い気がするので、.last
と付けた要素より、.first
と付けた要素の方が、後々、影響を受けないことが多い気がします。なんとなくですけど。
数年後、:last-child
がどんな案件でも使えるようになったら、margin-bottom派に移行するかもしれません。現状は、margin-topの方が利点があると思っているので、margin-top派です。
もし、margin-top派だと面倒な事例があれば、ツッコミいただけると嬉しいです。