:not(:empty) with space in CSS


I would like to apply a CSS rule on a div when it is empty. Problem: the application which generate the html puts a space:

<div class="my-div"> </div>

So I tried:

.my-div:not(:empty) {...}

But it doesn't work because of the space.

How can I do that in CSS ?

Thank you

Problem courtesy of: skurty


You cant


The :empty selector is the only way in CSS of detecting content, and also proves positive for whitespace:

The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered. Comments or processing instructions do not affect whether an element is considered empty or not.

Dont forget about the separation of concerns, HTML for content, CSS for styling and JS for functionality - as such, you either need to remove the whitespace from your HTML (content) or apply a class depending on its presence, or strip it using JS (functionality).

With that said, elements only containing whitespace should collapse by default, so long as the space in question isnt a non-breaking space

Demo Fiddle

Solution courtesy of: SW4


May be you try this;

  display: inline-block;
  width: 0px;
  height: 0px;

If the div is empty, otherwise you should set a another class by javascript if get content

Discussion courtesy of: Luis P. A.

Since you cannot do this with CSS ... here are 3 javascript lines that implements a CSS content selector called ":hasText" in jQuery.

$.expr[':']['hasText'] = function(node, index, props){
  return node.textContent == props[3];

You can use it in your problem like this:

$('.my-div:hasText(" ")').css({
  'background': 'red',
  'other css rules': '...'

Here is a DEMO with that same code implemented.

Discussion courtesy of: rafaelcastrocouto

This recipe can be found in it's original form on Stack Over Flow.