The P tag that holds the IMG tag needs a unique class

When adding an image with markdown, the images is wrapped in a stand-alone “p” tag.

![](https://cdn.motor1.com/images/mgl/17Ke9/s6/2020-mid-engined-subaru.jpg)

yields

<p>
    <img src="https://cdn.motor1.com/images/mgl/17Ke9/s6/2020-mid-engined-subaru.jpg" alt="">
</p>

It would be awesome to be able to add a class to that P tag for all kinds of important styling reasons. Since all P tags have no attributes in markdown, there is no way to target the P tags that only hold images.

Even if this P tag had a hardcoded class by default, that would be amazing. there is no need to all the customization of this P tag on the fly. However, just kicking out a different P tag would make this great for devs that have to style the parent element that hold this image.

Example output could be:

<p class="md_image">
    <img src="https://cdn.motor1.com/images/mgl/17Ke9/s6/2020-mid-engined-subaru.jpg" alt="">
</p>

The is no way to select the PARENT of an element in CSS. That’s why adding a class to the P tag that holds the image would be super helpful for those of us that have to style sites that render markdown to html.

There was some discussion about adding optional classes via a consistent attribute syntax.

However, the HTML version is totally fine as well. It’s more long winded, but it it will work with every CommonMark implementation.

I don’t think the spec should include a default class because that could clash with other classes on the page. But perhaps your specific renderer could add a class in a post processing step. Another option would be to add a CSS rule to add particular styling to all p tags within the div that contains the contents of the Markdown document.

1 Like

I see your point about wanting to avoid a “class clash”.

The CSS styling you suggest won’t work because an article written with markdown will have many generated paragraphs, and all of them with have the same attributeless P tag. Something like div p > img is still only selecting the IMG tag.

I’m using Hugo as a static site builder and the client wants to have control over the P tags that hold the IMG. I’ll drop with their GoldMark parser.

Thanks!!

You might be able to find a polyfill for the The Relational Pseudo-class to style those specific paragraphs with images. But I think the easiest option would be to just do post-processing of the generated HTML in Hugo to add classes to specific paragraphs based on your criteria.

1 Like

There are several extensions to support late HTMLʼs <figure> element for paragraphs that contain a single embedded image. They should work well for your use case, perhaps with minor alterations.

Ok! I’m totally mind blown at the moment! I just found out that the latest Version of Hugo comes with a new Markdown renderer called Goldmark and it JUST added a Render Hook for Images and Anchors.

So, I just implemented it and it works like a charm!

Thanks the suggestions guys!