Search code examples
javascriptmarkdownsvelte

Styling Markdown output


I'm using Sveltekit & SCSS for my development.

I've been trying to use the marked npm package to get Markdown onto my site. I've been able to get markdown working, but having trouble styling the output that it's displaying. All of this is within a .svelte page.

This is a the code for the output of the Markdown

import { marked } from 'marked';
import DOMPurify from 'dompurify';

let markdownContent = '';
let clean;

markdownContent = setups[0].description;

clean = DOMPurify.sanitize(marked(markdownContent));

This is the output of the Markdown code Markdown output Dev tools output

I've tried adding in css at a global level for example h1, h2, h3, etc. But no styles I do apply to the markdown that is being output.

I've looked into my css and everything else has a style applied so i can only believe it's working correctly.


Solution

  • Styles are only really global if you use a :global() pseudo class on them (see docs), so to style the headings you can do something like:

    <style>
      :global(h1) { font-size: 1.5rem; }
      :global(h2) { font-size: 1.25rem; }
      ...
    </style>
    

    Would recommend nesting that in a static element in the component, so the styles do not leak to the outside:

    <div class="markdown" use:markdown /> <!-- action to add markdown here -->
    
    <style>
      .markdown :global(h1) { font-size: 1.5rem; }
      .markdown :global(h2) { font-size: 1.25rem; }
      ...
    </style>
    

    (Using svelte-preprocess you can have global <style> elements or blocks.)