Enhancing Our Components with CSS :empty

While building a component, we sometimes don’t think about what will happen in case there was no content. How does it will look? In CSS, we have a useful pseudo-class :empty that provide us with the ability to check if the content of an element is empty or not. In this article, we will explore some use cases and real world examples where :empty can be useful.

1. Figure Element

HTML has an awesome element called <figure>, it provide us with the ability to add an <img> in addition to a caption by using the element <figcaption>. In some cases, we want to keep the caption empty, in case it has padding and a background color, then it will look empty and bad. :empty to the rescue!

2. Article tag

On any news website, it’s important to have different categories for the articles. We can place a category tag on each article to let users explore that category if they are interested. In some edge cases, we don’t have a clear category for an article so we leave it empty.

By using :empty, we can hide it completely to prevent any unwanted look.

3. Alerts

Each website needs to provide users with alerts and updates when they need to. For example, an alert that prompts when a user clicks on submit button without finishing the whole form. What if the alert doesn’t have content? It will look empty and weird.

4. Showing a message

In some cases, when we have an empty element, we want to replace it with a warning or something to indicate that there is an issue. We can revert some styles and add content using :after or :before pseudo-elements.

.post-time:empty{border-left:0;padding-left:0;font-size:90%;}.post-time:empty:after{content:"No specified date for this post.";opacity:0.5;}

5. Hide Separators

Nowadays we depend a lot of CSS to add borders and separators between elements. I realized lately that it’s better to use the default <hr/> element for separating important things. For instance, a paragraph followed by a short sentence, we want to separate them with a <hr/>.

In case there is no paragraph, I want to hide the separator because there is no need for it. By using CSS adjacent sibling selector (next-sibling selector), I will hide the <hr/ that is placed after the .content element.