How to Add a Class to a Tag in Rich Text?

For example, I would like this to be output this with the rich text field:

<h2 class="marginBottomNone">This Heading Has No Bottom Margin</h2>
<p>This is a Strap Line Related to the H2 Above</p>

The above happens frequently in our content and I’m trying to figure out how to output it with Storyblok. And, there are lots of other cases where we need to add a class directly to a tag.

I can add a span with a class inside the h2 using the: Rich Text | Edit Field | CSS Class Options
But, that adds a span inside the h2 and not to the h2 itself.

1 Like

Hello Ed,

which rich-text renderer are you using for the content?

Hello Hannes, I’m using the richTextResolver from the JavaScript SDK.

My colleague has taken a look at the issue and written a comment on Github:

Thanks Hannes, these are two separate questions though.
What I am asking here is:

  • For content added by Rich Text, is there a way to add a CSS class to a tag instead of adding a nested span tag and adding the class to that?

For example, if I add a class to a paragraph in the rich text editor (Rich Text | Edit Field | CSS Class Options), the output looks like:

Hello World!

But, the desired result is:

Hello World!

I need this in order to apply margins directly to the paragraph tag.

I’m sorry Ed. I was a little bit too fast with the answer :sweat_smile:

My colleague made an example that shows how to provide your own schema for the rich-text resolver which allows you to do what you want:

I wish you an awesome weekend!


1 Like

Thanks Hannes and Alexander, that worked perfectly!

1 Like

This was a huge help, and when implemented, I can confirm in dev tools that the class is getting added to the proper tag. However, once I attempt to save within Storyblok, the class is removed.

Any thoughts on why saving would break it?

What’s interesting is that after you save the page it disappears, but if you navigate to the page within Storyblok, Nuxt is hydrating the page with the class intact. Once you refresh the page though, the class disappears.

Also, after deploying Nuxt, the class is not there, even if you navigate to the page.

Within Nuxt, checking if it’s already been processed works.

MySchema.nodes.heading = function(node) {
    let attrs = {}

    if (node.processed) {
        attrs = node.attrsCopy

    if (node.content && node.content.length === 1 && node.content[0].marks && node.content[0].marks.length === 1 && node.content[0].marks[0].type === 'styled') {
        attrs = node.content[0].marks[0].attrs
        node.attrsCopy = attrs
        node.processed = true
        delete node.content[0].marks

    return {
        tag: [
                tag: `h${node.attrs.level}`,
                attrs: attrs