How to Style Contents in dangerouslySetInnerHTML with Tailwind
I recently needed to style the Html content that was injected into an element using the dangerouslySetInnerHTML
property. Since the other parts of the project were using Tailwind, I wanted to continue the same approach here instead of writing custom CSS for that part. Turns out Tailwind makes this relatively easy using the arbitrary variants. This allowed me to do the following:
const Tooltip = ({ content }: { content: string }) => (
<div className="bg-white">
<div className="[&>p]:text-zinc-800"
dangerouslySetInnerHTML={{ __html: content }}
/>
</div>
)
Essentially you can target any element using the [&>element]
syntax. Tailwind itself for example has an example of [&:nth-child(3)]
, and in case you need to style for example all the p
elements in the dangerouslySetInnerHTML, not just the direct descendants as in the example above, you can use underscore: &_p
as replacement for space in your selector.