add css content text in 'empty' divs

xanld picture xanld · Nov 11, 2013 · Viewed 12.5k times · Source

See this fiddle: http://jsfiddle.net/xanld/3yh28/

div:before {
    content: 'This div is empty';
}
div:empty {
    background:red;
}

I'd like to add css content to empty divs only. I can either use the :empty selector, but I need to use the :before selector in order to add content. Is it possible to use both?

Thanks.

Answer

sinelaw picture sinelaw · Nov 11, 2013

Yes, you can use both - see updated fiddle: http://jsfiddle.net/3yh28/1/

div:empty:before {
   content: 'This div is empty';
}

Make sure it's :empty:before (not :before:empty), because you want to apply the pseudo-element :before on the element that matches div:empty.

By the way, :empty is CSS3 and not supported on old browsers (such as IE8, or about 40% of the browser market share)