Padding vs children with margins

旧街凉风 提交于 2019-12-05 08:43:41
BoltClock

It's anything but better. There is no sense in trying to add padding to a box using other methods when a CSS property made for this exact purpose, padding, has existed since pretty much forever.

Anyway, one counter-example I can think of is the fact that adjoining vertical margins can collapse.

There are several ways to cancel margin collapse (heck, giving an element padding is one!), but these methods aren't designed for preventing margin collapse as much as they do so as a side effect, and there is no simple "off switch" for collapsing.

Authors who don't understand the nature and the purpose of collapsing will find themselves having a world of trouble dealing with it. If you're going to use margins to simulate padding you may be in for a hard time. It's not worth it.

Your given markup is a prime example of when margin collapse can happen unexpectedly and cause headaches: if there are no other styles on your .caption element (like borders or padding), the margins of .captionContainer will combine with those of .caption, resulting in something like this happening. In the same vein, it's a great counter-example of when trying to simulate padding using margins ends up backfiring.

Compared to the potential issues caused by margin collapse, I honestly find your suggestion of using box-sizing: border-box a good case against using margins to simulate padding, while preserving the exact widths that you need because it's designed to solve that problem. Browser support is fairly decent too (IE8+), so unless you're designing for really old browsers, it should be OK to use it.

There are several other potential pitfalls of using margins to do things that padding was clearly made to do, but margin collapse is one of the biggest issues you'll face.

Explain him this way:

Margin is on the outside of block elements while padding is on the inside.

Use margin to separate the block from things outside it, and padding to move the contents away from the edges of the block.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!