Hiding a list with no items in CSS

The Artemis reading interface consists of a section tag for each day for which there are blog posts to show. Each section contains a h2 denoting the date the posts were published, and a ul that lists each post published on that date.

Here is what the interface looks like:
The Artemis interface showing three posts, one published on May 26th and two published on May 25th. ALTThe Artemis interface showing three posts, one published on May 26th and two published on May 25th.
There are some niche scenarios where a list may end up with no items but still retain the heading (and, as I later discovered, some practical scenarios too).

This got me thinking: could I write a CSS rule that would hide an entire section if the list in the section had no child li elements? I first looked at the :empty CSS psuedo-class (MDN docs for :empty), but :empty is sensitive to white-space. If a ul had no child elements but a single space between its opening and closing tags, :empty would not apply.

With that said, with the :has selector I can achieve the effect I want!

I ended up with the following rule:
section:not(:has(.list-entries > li)) {
display: none;
}

This rule says that a section should be hidden if it does not have an element with the class .list-entries (which is a ul) that contains at least one li. NB: If you use a similar rule, you may want to make this only apply in a particular context, i.e. your main tag.

One nice effect of this rule is that, because it is CSS, the rule will be applied as the page changes. For example, Artemis has a feature to hide posts. When you press the hide button, an element appears saying a post is hidden and shows an undo button that hides after a few seconds. This message shows using JavaScript. With the CSS rule, if you hide all posts, when the last undo message goes away, the whole section can disappear without having to use JavaScript to find the parent section and delete it. Indeed, the less JavaScript I have to write, the better.

Here is how the effect looks:

When the last post in the ul in a section is hidden, the whole section, including the heading, disappears. When the page is refreshed, the section will also be hidden because the back-end will have been notified that the user wants to hide the post.

I thought I'd document this in case it is helpful for anyone else!

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论