Hide widget if empty

Asked

Viewed 1,705 times

15

I have a div which is used to display alerts to the user:

<div id="page-alerts" style="margin:25px 0;"></div>

Problem

Example in Jsfiddle

For reasons of formatting, it contains margins above and below, causing a blank space equal to the value of the margins, when empty, which breaks the layout.

Captura de Tela com indicação do problema

Question

How to hide the div when it is empty (no alerts...) ?

  • Put <div id="page-Alerts" style="margin:25px 0; display:None"></div> , and when the alert is issued take "display:None"

2 answers

15


You can use the pseudo-selector :empty in your CSS to handle childless elements (text or sub-elements)

#page-alerts {
     margin:25px 0;
}

#page-alerts:empty {
     margin: 0;
}

Example in jsFiddle. This selector works on all browsers except IE8 or earlier. In the example above I have margin as 0, but you could use for example display: none if you want to hide the element at all.

Note: this rule worked well on your fiddle because you used CSS to assign style; if you assign style inline (as in your question code) so I think it will take precedence over the CSS rules. In this case, only using Javascript to solve. Example:

$("#page-alerts")
    .toggle(!$("#page-alerts").is(":empty"))
    .bind("propertychange DOMSubtreeModified", function() {
        $(this).toggle(!$(this).is(":empty"));
    });

(Source code to listen for modifications in div: this answer no SOEN; no mention of which browsers support the event DOMSubtreeModified, but that other answer says he can be replaced by propertychange in IE)

  • Great example @mgibsonbr, I didn’t know about this selector. I believe it looks better the way you did, than it does with "display:None"

0

Set the div as default

display:none

Then when filling the div with the content put the

display:block

If you use Jquery

$(elemnto).show()
$(elemnto).hide()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.