How to space the children of a div with css?

前端 未结 8 716
-上瘾入骨i
-上瘾入骨i 2021-02-03 17:37

I want a gap of say 30px; between all children of my div. E.g if I have:

...

8条回答
  •  萌比男神i
    2021-02-03 18:24

    For an unknown amount of children you could use.

    #parent > * {
        margin: 30px 0;
    }
    

    This will add a top and bottom margin of 30px to all direct children of #parent.

    But img is not displaying as block default, so you may use:

    #parent > * {
        display: block;
        margin: 30px 0;
    }
    

    Vertical margins of block elements will be collapsed. But you will have margins at top and bottom of your parent div. To avoid that use the following code:

    #parent > * {
        display: block;
        margin-top: 30px;
    }
    
    #parent > *:first-child {
        margin-top: 0px;
    }
    

    This will only add top margin and removes that top margin for the first element.

提交回复
热议问题