Padding on parent versus margin on child

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

    Consider what kind of gutter you want to add. Is it to seperate elements from each other? Is it to create space inside an element?

    For gutter on all sides of an element, like the blue in your example:

    enter image description here

    Here, I'd use padding on the container. Logically, that's exactly what I want, so why consider anything else?


    For gutter between elements on a row, like the space between the green elements in your second example:

    enter image description here

    Here, I'd use margin on the green elements. There's obviously a margin between them, so padding doesn't make a whole lot of sense.


    When you use these two examples together, however, they create a problem where the margin on the green elements may be conflicting with their parent's padding. I manage this by removing the margins from the first and last children.

    Additionally, you may want more of those fine, green elements on a new row. I usually clear on every row using an element wrapping the entire row with whatever appropriate method to clear the floats, so it makes a lot of sense to seperate the rows with a margin. Obviously, the same conflict with the parent's padding arises here, but it's easily handled in the same way (ie, removing the margin from the last row).

    So, in short:

    • Padding on parent elements for gutter between its edges and its children.
    • Margin to seperate elements with the same parent from each other.
    • Remove margins from said children when its margin connects to the parent's padding (the first and/or last children in a row, the last child in a column).

    Disclaimer: This is how I do things. I can't promise it's the most efficient way to do things, but it's the way that makes the most sense to me.

提交回复
热议问题