5

让我们先说我了解盒子模型。在我作为开发人员的短暂时间里,我一直试图非常密切地使用语义 html 并使用响应式设计实践。我最近在一家新公司找到了一份 Jr. Developer 的工作,而我的 Sr. 坚决反对填充。就像他不想在任何情况下使用它一样。他希望我在所有东西上使用设置的高度和宽度,如果我需要模拟填充,我必须使用边距添加一个子 div。例如:

<div class="caption" style="padding: 5px;">
   Caption
</div>

需要成为

<div class="caption">
   <div class="captionContainer" style="margin:5px;">
       Caption
   </div>
 </div>

我试图弄清楚为什么会这样,以及我怎么可能解释为什么我认为这很糟糕,但它不起作用。这对我来说似乎很不对劲。他说这是因为 padding 拉伸了元素的宽度,对此我用 box-sizing:border-box 回应。

我必须按他说的做,但有时我们会谈论它,他似乎确实接受了我的建议,但我认为我说的不是正确的事情。它实际上更好吗?如果不是,为什么?

这个问题可能会因为有点讨论而被关闭,但这让我发疯了,我不知道还能去哪里。

提前致谢!

4

2 回答 2

1

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.

于 2012-11-25T08:43:21.183 回答
0

用这种方式解释他:

边距位于块元素的外部,而填充位于内部。

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

于 2012-11-25T08:37:25.007 回答