markdown generated html is not styled by the styles specified by css

333 Views Asked by At

Good day,

I am trying to create a markdown previewer using Svelte. I'm using the following libraries for different tasks:

  • Marked library for parsing markdown,
  • Highlight.js for highlighting code blocks,
  • Sanitize-html for sanitizing the generated HTML to prevent XSS attacks.

However, I'm facing an issue where the custom CSS classes I apply to the generated HTML are not being applied. Here is the code I'm using:

<script lang="ts">
  import sanitizeHtml from 'sanitize-html';
  import { marked } from 'marked';
  import hljs from 'highlight.js';
  import { afterUpdate } from 'svelte';
  import 'highlight.js/styles/atom-one-dark.css';

  let markdown = `# Hello World`;

  $: html = sanitizeHtml(marked(markdown));
  afterUpdate(() => hljs.highlightAll());
  let edit = true;
</script>

<div class="container">
  <div class="editor">
    {#if edit}
      <textarea spellcheck="false" bind:value={markdown} />
    {:else}
      <div class="viewer">
        {@html html}
      </div>
    {/if}
  </div>
  <div>
    <input type="checkbox" bind:checked={edit} />
  </div>
</div>

<style>
.viewer h1 {
  font-size: 24px;
  color: #ff0000;
}
</style>

The generated h1 element is not styled

I thought it might be because of the dependencies conflicts so I tried removing every dependencies but still no class is applied.

1

There are 1 best solutions below

2
brunnerh On

Svelte styles are scoped by default, you need to use :global() to prevent scoping in this case as the HTML generated via @html will lack the classes used for scoping, e.g.

.viewer :global(h1} { ... }

(If you use svelte-preprocess you can create entire :global blocks with nested rules to reduce redundancy, this may require an additional pre-processor like PostCSS, SASS or LESS to be installed.)