Padding on parent versus margin on child

前端 未结 4 1517
渐次进展
渐次进展 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:54

    I prefer to set margin on the div that resides inside the container.

    Suppose the black div below is the outer container with display: flex, width: 300px and height: 200px. When you assign padding: 30px padding to the outer div, this will result in 360px in width and 260px in height. Given that you won't expect the container to stretch, this will affect the elements around the container div. Hence, it is better to use margin on the inner div.

    enter image description here

    When you assign margin between the inner div and the container, the actual outer div won't move, and the margin will only affect the inner div, thus not affecting the elements around it.

    If you are using box-sizing: border-box; then things will change accordingly, so it totally depends on what actual size the elements has to be. Using margin/padding on the inner elements will be the right way.

提交回复
热议问题