Remove padding for an empty element

前端 未结 8 466
灰色年华
灰色年华 2021-02-02 05:32

I\'m generating a page for an upcoming portal site, and I\'ve got an HTML element with some optional content. I\'d like the element to not render if it is empty, but adding some

相关标签:
8条回答
  • 2021-02-02 06:09
    <style>
    .someElement{padding-top: 5px; display:table;}
    </style>
    <div class="someElement">With padded content</div>
    <div class="someElement"><!-- shouldn't render since it has no content --></div>
    

    Adding display:table; should do the trick.

    0 讨论(0)
  • 2021-02-02 06:09

    At the point where you populate the optional div, if there is no text to put in it, try changing the CSS display property to none. According to this source (and others), display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

    0 讨论(0)
  • 2021-02-02 06:13

    If it's necessary to have the div.someElement in the HTML, the best CSS/HTML way to do that would be to add an extra div around the added content that has the padding property

    .someElement > div{padding-top:5px;}
    
    <div class="someElement"><div>Content</div></div>
    

    Otherwise, do as Pekka says, or take a look at having javascript do it for you.

    0 讨论(0)
  • 2021-02-02 06:21

    I can't think of a CSS only way to do that.

    I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution.

    0 讨论(0)
  • 2021-02-02 06:24

    You can do the trick with the CSS3 pseudo-class :empty

    .someElement
    {
        // your standard style
    }
    .someElement:empty
    {
        display:none;
    }
    

    Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine...

    0 讨论(0)
  • 2021-02-02 06:26

    Give the empty element a different class (say someHiddenElement) when you are generating the content. Then add someHiddenElement { display: none } to your style sheet.

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