DEV Community

Berra
Berra

Posted on • Updated on

Tiny css separator

Ever had a case where you want to separate some test with a special character. But maybe some content is dynamic. And if not the first is visible - then the separator would be out of place - right?

This is a little solution I came up with in css using data attributes, empty selector and sibling selectors.

*:not(:empty) + [data-before]:before {
  content: " " attr(data-before) " ";
}
Enter fullscreen mode Exit fullscreen mode

Use like this

Use it like this with some conditional JSX syntax.

<p>
  {tags && <span>{tags}</span>}
  {date && <span data-before="-">{date}</span>}
</p>
Enter fullscreen mode Exit fullscreen mode

This would output Tagname - May 4:th 2023 if tags is available. And May 4:th 2023 when no tags are available.

How it works

From left to right top to bottom. The star * selector looks at every element. And then the :not(:empty) will take any element that has content inside. That is not empty! Then we have the + that will select the very next element after that. That element must have a data-before attribute. And then we add the :before pseudo element. In that before element we add content with spaces before and after and the content from the data attribute data-before.

Hope this was useful or educational or something like that.

Until next time, Cheers!

Top comments (0)