How to remember in CSS that margin is outside the

2020-02-17 08:42发布

I don't edit CSS very often, and almost every time I need to go and google the CSS box model to check whether padding is inside the border and margin outside, or vice versa. (Just checked again and padding is inside).

Does anyone have a good way of remembering this? A little mnemonic, a good explanation as to why the names are that way round ...

15条回答
\"骚年 ilove
2楼-- · 2020-02-17 09:22

Print the diagram from the Box Dimensions section of the specification, and put it on the wall.

查看更多
爷的心禁止访问
3楼-- · 2020-02-17 09:22

PAdding is a PArt of an element's PAinting: it extends the element's background. It makes sense to think of a pair element+padding as sharing a common background. Padding is analogous to the painting's canvas: the bigger the padding, the bigger the canvas and therefore background. Border (the painting's frame) would go around that pair. And margin will separate paintings on the gallery wall. Thinking about the concept of object background helps glue the pair object+padding together. The usual explanations of what is inside vs outside do not stick to memory: after a while everybody gets back to the original confusion. Remember also that margins are vertically collapsible and padding is not.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-17 09:22

Instead of ask again and again to google you just use inspector window. In that style tab and scroll down to bottom you can see like this.

enter image description here

查看更多
做自己的国王
5楼-- · 2020-02-17 09:27

pin - P is in

查看更多
倾城 Initia
6楼-- · 2020-02-17 09:27

I've just learnt it over time - the box model is fairly simple but the main reason people find it hard is because body doesn't visibly break the model.

Really, if you give body a margin and a background you should see it surrounded by a white strip. However this isn't the case - body's padding is the same as margin. This establishes a few incorrect things about the box model.

I usually think about it like this:

  • margin = spacing around the box;
  • border = the edge of the box;
  • padding = space inside the box.
查看更多
家丑人穷心不美
7楼-- · 2020-02-17 09:28

I know this is an answer to your question, but more of a tip. Whenever I am dealing with margin and padding, I will add a border around the part you are working with, then from there, it shows me the room I have to work with. When I am all set, I remove the border.

查看更多
登录 后发表回答