Why CSS Classes Don’t Work with dangerouslySetInnerHTML in Next.js (and How to Fix It)

Published: (December 16, 2025 at 02:54 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

The Problem

When working with SEO‑driven or CMS‑based content in React / Next.js, we often rely on dangerouslySetInnerHTML to render HTML strings. Everything looks fine… until you add CSS classes inside the HTML content and realize the styles are not being applied at all.

Example content

const content = `
  You can consult certified nutritionists
  from home.
`;

Rendered like this:

And styled using styled‑jsx:

{`
  .highlight {
    color: #0a7cff;
    font-weight: 600;
  }
`}

Result: The .highlight styles do not apply.

Why: Next.js uses styled-jsx, which scopes CSS to JSX‑rendered elements. Outside the styled-jsx scope, a selector like:

.highlight { ... }

gets transformed into something like:

.highlight.jsx-123456 { ... }

But the injected HTML does not receive that hash, so the styles never match.

Fixing It

Wrap your class selectors with :global() so they are not scoped.

{`
  :global(.highlight) {
    color: #0a7cff;
    font-weight: 600;
  }

  :global(.link) {
    color: #0070f3;
    text-decoration: underline;
  }
`}

Now the injected HTML works correctly and the styles are applied as expected.

Back to Blog

Related posts

Read more »