Padding on parent versus margin on child

前端 未结 4 1505
渐次进展
渐次进展 2021-02-05 12:11

When I want to place some (logically meaningful) div inside a (logical) container div with some space apart as below,

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 12:50

    There is no hard-and-fast rule on this, because it all depends on context, and in complex designs, you usually have no choice but to use one or the other to get the desired result.

    That said, you should try to group logically related rules together. For instance, when you have two HTML elements on a website that serve a similiar purpose, e.g. your outer

    and another similar box (that should get no padding), then, all else being equal, it is better to set a margin on the inner
    .

    If, however, you are placing more than one element into the outer

    , then you should in fact use a padding, because that takes care of all inner elements at once. @zzzzBov's answer works as well, but it relies on margin collapsing, which can be tricky to deal with.

    edit: In your second situation, I usually combine padding and margin, like this:

    .outer {
        padding: 10px 15px 10px 5px
    }
    
    .inner {
        margin-left: 10px
    }
    

    Probably looks complicated, but works regardless of margin collapsing and has served me very well.

提交回复
热议问题