I'm trying to set style for a <div>
following an empty <ul>
.
This is simple code i'm currently testing: (OS is win7)
HTML:
<button class="btnAdd">add new LI</button>
<button class="btnRemove">remove last LI</button>
<ul></ul>
<div>Should be red if UL is empty</div>
CSS:
ul:empty + div {
color:red;
}
jQuery: (not relevant to issue, just for testing purpose)
$('.btnAdd').on('click', function () {
$('ul').append('<li>LI</li>');
});
$('.btnRemove').on('click', function () {
$('ul').find('li').last().remove();
});
Expected behaviour:
In all major browsers, when adding element to <ul>
, style set for empty <ul>
following <div>
shouldn't be applied. When removing all <li>
, style should be reapplied to targeted <div>
.
Current behaviour:
:empty
pseudo-class as by default, not reacting to any content added or removedGoogling it, i've find some workarounds but most seem outdated and none fix issue here, none i can't find at least.
For chrome, i've found that setting a CSS rule :empty
for UL fixes it, but really i don't know what's going on: ul:empty {}
(ya this is an empty CSS rule?!) <-- I guess now it forces an UI repaint on chrome ?!
Unfortunatley, this doesn't fix behaviour on IE10/11.
UPDATE 1:
Seems like bug is related to next sibling selector +
, even using ~
doesn't give consistent result on chrome. But if applying style directly to :empty
element, all seems to work correctly on all browsers: http://jsfiddle.net/EyEa7/
But my goal here is to target sibling element of :empty
element, not the empty element directly.
UPDATE 2:
Forcing an UI redraw fixes it on all browsers, e.g using $('body').hide().show(0);
once content has been updated: See DEMO forcing redraw
But, i'd really more appreciate a fix which doesn't involve any javascript code.
The question now could be:
The CSS :empty pseudo-class selects any element that does not contain children for a given selector.
The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments, processing instructions, and CSS content do not affect whether an element is considered empty.
The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".
Something like this will work, but it's not particularly pretty:
ul:empty {}
ul:empty + div {
color: red;
}
ul + div {
animation: repaint 1000s infinite linear;
}
@keyframes repaint {
from { zoom: 1; }
to { zoom: 0.99999; }
}
See: http://jsfiddle.net/vd2Hx/
Tested in Chrome, Firefox, Safari, Opera, and IE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With