How to add vertical spacing between block elements, but not top and bottom

前端 未结 5 721
余生分开走
余生分开走 2021-02-02 13:51

Say I have a bunch of P, LI, or DIV elements, with nothing between them. I want to control the vertical spacing between them, so they don\'t fit so tightly. But I don\'t want

相关标签:
5条回答
  • 2021-02-02 14:13

    Use adjacent selectors

    p + p { margin-top: 10px; }
    

    Basically the concept is that, if a p comes after another p give 10px margin in between.

    You usage is something similar to

    p + p, li + li, div + div { 
        margin-top: 10px;
    }
    
    0 讨论(0)
  • 2021-02-02 14:24

    This can also be done using :last-child or :first-child

    Here is an example:

    p, li, div {
        margin-bottom: 10px;
    }
    
    p:last-child, li:last-child, div:last-child {
        margin-bottom: none;
    }
    
    0 讨论(0)
  • 2021-02-02 14:28

    You can use adjacent selectors. You can define like this:

    p + p{
     margin-top:0;
    }
    

    OR

    p ~ p{
     margin-top:0;
    }
    
    0 讨论(0)
  • 2021-02-02 14:28
    p, li, div {
        margin-bottom: 10px;
    }
    #parentID {
        margin-bottom: -10px;
    }
    
    0 讨论(0)
  • 2021-02-02 14:28
    p { margin: 10px 0 0 0; }
    p:first-child { margin: 0; }
    

    That is, set a top margin of 10px for all p elements and other margins to zero, except for the first p element, for which you set even the top margin to zero.

    This works more widely than many other approaches, which use contextual selectors that are not supported by old browsers. To get really maximal browser support, you would assign a class to the first p element in markup and use a class selector instead of p:first-child.

    This is the simplest possible way, since CSS operates on elements, not on what’s between elements. So you need some way of distinguishing the first p element in a sequence of p elements.

    Note that p { margin: 5px 0; } (mentioned in the question) would create vertical margins of 5px, not 10px, because adjacent vertical margins collapse.

    0 讨论(0)
提交回复
热议问题