Question

I'm trying to set style for a <div> following an empty <ul>.

This is simple code i'm currently testing: (OS is win7)

Basic jsFiddle DEMO

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:

  • Firefox handles it with no problem, get expected result.
  • Chrome removes red color for following DIV when UL is no more empty, but doesn't reapply it when UL is empty again (removing all LIs from UL)
  • IE10/11 just apply CSS :empty pseudo-class as by default, not reacting to any content added or removed

Googling 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 ?!

Fixed jsFiddle for chrome

Unfortunatley, this doesn't fix behaviour on IE10/11.

So anyone knows a way to make it works on all major browsers???

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:

  • How can i force IE10/11 to repaint UI using only CSS? (hoping this is a relevant question regarding this issue)
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top