Should I take advantage of margin collapsing in this code example?

Hello,
I’m using the Hugo static site generator, and I’ve noticed that when I have a numbered list, sometimes the first sublist is a paragraph, and other times it’s not. I can’t modify this behavior because it’s likely controlled internally, so it’s not “customize the theme” related. I’m trying to demonstrate the issue with a simple HTML example.

Notice that when the first item in the sublist is a paragraph, there’s a gap between the list item and the paragraph. I’m talking about item 3.

I don’t like that gap, but it makes sense because paragraphs have a top and bottom margin by default, right? I can target the paragraph only in the sublist and remove the margins:

ol ul p {
  margin-top: 0;
  margin-bottom: 0;
}

This fixes the issue. You can uncomment that on codepen to see what I’m talking about.

The issue is that I want the code block to always have some margin at the top and bottom. Currently, it has a top margin when there is a paragraph above it (that’s because the paragraph has bottom margin by default), but otherwise, it doesn’t. In cases where there is sometimes a paragraph above the code block and sometimes not, would it be better to set a top and bottom margin on the code block div itself, ensuring that it doesn’t exceed the margin of a regular paragraph? That way, if a paragraph is present, it won’t add the set margin to the paragraph margin so the gap won’t be too big. There will be a margin collapse if there is a paragraph present, otherwise not, but the spacing will be consistent.

Not 100% sure what you’re looking for but if you always want a margin around the code block, then add it to the class.

.codeblock {
  background: #f0f0f0;
  margin-block: 1em;
}

Then I would tweak your original to only clear the margins for the first p element in the list

ol ul p:first-of-type {
  margin-block: 0;
}

Those two give you this look:
image

NOTE: margin-block: 0 is the same as your margin-top/margin-bottom. It affects both properties and is pretty well supported browser wise.

2 Likes