Using the :empty selector to identify an empty HTML block using only CSS

Partha Roy
2 min readMay 24, 2018

Yesterday I came across an interesting challenge of how to identify a DOM element having no content inside and apply some styles to that HTML element.

There was no DOM manipulation involved and the task was purely to have a different style, so I tried to check CSS ways to do it and that’s where this underrated CSS3 selector came to the rescue.

The problem is not showing anything or having some different styles for the container element if there is no content inside that.

Thought Process: The first thing that will come to most of our minds is some lines of quick and dirty Javascript code that will suffice this requirement, But there’s a great CSS pseudo-class available out there which is created for this kind of situation and it is great to use also.

Introducing ( if not known already ) the :empty selector

The :empty selector can be used to add or modify any kind of style to an element which doesn’t have any child element or text. As the MDN documentation says,

The :empty CSS pseudo-class represents any element that has no children. Children can be either element nodes or text (including whitespace). Comments or processing instructions do not affect whether an element is considered empty.

Also, It has wide Browser support from IE9 to Safari, so it’s an elegant and lot more faster solution than using Javascript.

Please check the working JsFiddle Demo here -

https://jsfiddle.net/5vye98ay/3/

Please let me know your views on it in the comments. :)

--

--

Partha Roy

Full-Stack Engineer 👨🏻‍💻 | ReactJs Dev ⚙️ | Tech Mentor 👨🏻‍🏫