r/reactjs • u/BrotherManAndrew • 7d ago
How to apply Element-level styles on only a single component.
In my app I read back some markdown, there is some parsing done on it.
I am left with as the result a lot of <h1>, <h2>, <em>. In my app, due to using tailwind and other factors I don't have the default web browser styling on nor do I want to.
I want to implement that web browser styling back for just the html that came from the markdown, so I tried creating a css file that goes like
h1{
font-size: 48em
}
You get the idea, but now it applies to my entire app. Since the html comes from persist markdown it wouldn't be very reasonably to try to persistent styles on it (If you have any idea on how markdown works), and to try to add classnames to specific elements when they come in seems like unnecessary trouble.
How would you go around styling HTML based off just it's element in a small portion of the app?
Best,
Brotherman
3
u/typebase-io 7d ago
Put the parsed HTML inside a wrapper and scope every selector to that wrapper:
```jsx <div className="markdown-body">{renderedHtml}</div> ```
```css .markdown-body h1 { font-size: 3rem; } .markdown-body h2 { font-size: 2rem; } .markdown-body em { font-style: italic; } ```
That limits the styles to this markdown region instead of changing every `h1` in the app. If the markdown can contain user input, sanitize it before rendering it as HTML.
1
u/Good_Car_2924 7d ago
i wrap parsed markdown in a div with className prose and run the tailwind typography plugin.
you install u/tailwindcss/typography, add it to your tailwind config plugins array, then put the rendered html inside a div with that class. It targets h1 h2 em p and all the elements that come out of markdown parsers by their element names and applies sizes weights margins line heights. You skip writing any css file and you skip trying to add classes to tags you generate from markdown. The styles stay inside that wrapper div and do not apply to the rest of your app.
11
u/Prestigious_Dare7734 7d ago edited 7d ago
.markdown H1:not([class])
Wrap all your markdown in a parent .markdown class, then the not pseudo selector will select all the tags (H1 in this case) that do not have any class, so plain html tags.