<img> tag wrapped in <p>


#1

I have some markup like this:

<p>Lorem ipsum dolor sit amet.</p>
<img src="img.svg" alt>
<p>Duis aute irure dolor.</p>

Surreal is wrapping the image in its own paragraph tag. I know that we rightly love <p> tags here but in this case it’s making a bad choice. Is there something I can do to hint to Surreal not to do this?


#2

This is also mentioned in the FAQ, but it’s worth reiterating here for others searching.

The editor strives to produce markup that is both valid and semantic. The use of paragraph tags is essential to this objective, despite its controversy. To better understand why paragraph tags are important from a technical perspective, refer to the article Why P Tags Are Your Friends.

You can remove the gap that p elements create by eliminating the margin in your stylesheet:

.cms-editable p {
  margin: 0;
}

Here’s an important section from the linked article that I also like to reference.

WYSIWYG editors do such a good job of hiding the way that HTML and CSS work, that people often forget that in the end we’re still trying to generate high quality, standards-compliant HTML output. We’re limited by what those standards and browsers can actually do, so removing important concepts like paragraphs makes it incredibly difficult to create an editor that works intuitively.

Ultimately, it’s not that we developers don’t want to support your use case, it’s just that the restrictions you’re asking us to abide by dramatically reduce our ability to deliver a high quality authoring experience.

For a proper editing experience, the editor requires a root node for each “block” inside a content region. By default, this is a paragraph.

If you don’t want paragraphs at all in a content region, you can enable an inline element such as a <span>. Of course, you won’t be able to put headings and other block-level elements in it, but your image will no longer be wrapped with a paragraph and hitting enter will give you a <br> instead of a <p>.

If this is a recurring thing in your website, you can also create a block with something like this:

<p class="image">
  <img src="img.svg" />
</p>

It’s still an extra tag, but you’ll be able to style it to avoid visual discrepancies. (You can also use a <div> instead.)

I hope that helps!


#3

Thanks for the info (and apologies as I suspect you’ve repeated it a thousand times!).

What was making me uncomfortable in may case was the semantics. Wrapping the image in a <p> implied that it was a bonefide meaningful part of the content. But in my case it’s a floating decorative image.

So I’ve taken your advice (and an example from the spec) and wrapped the images in <div>s.

Thanks for the education ^^


#4

No worries! There are certain tradeoffs we have to accept when working in the context of a CMS. After all these years, I’m confident the only way to achieve perfect markup is to maintain it by hand! :laughing: