queen.raae.codes · a developer’s logbook
1 min read

How to style `dangerouslySetInnerHTML` with Tailwind

Written in 2023, 3 years ago. Tools and advice may have moved on since.

I stumbled on this challenge when working with highlighting for Prune your Follows.

How to style the mark element in the possibly highlighted search result?

Turns out Tailwind has support for Using arbitrary variants, but it took me quite a while to find that in the documentation, I’ll tell you 🕵️‍♀️

const HighlighetResult = () => {
  return (
    <span
      className="[&>em]:bg-amber-300" // 👈👈👈
      dangerouslySetInnerHTML={{
        __html: highlight?.username || record.username,
      }}
    />
  );
};

Inside the [] in the code example, you may use any regular old css selector! So, for instance, if you are getting content from a third party, you could do [&>p], [&>img] etc. The > indicates direct descendant; for any img you’ll need to do [&_img], the _` will be read as a space.

The resulting styled highlight

 

All the best,
Queen Raae

Join the crew!

All the shenanigans from me and my piratical family, straight to your inbox.

Search the log

↑↓ to move · Enter to open · Esc to close All entries →