Search code examples
cssmargin

Uncollapsing margins between in-flow siblings


This is what makes me cry at night. One would wish that CSS had a directive margin-collapse:none;, but alas, that is from my imagination.

How do you get two in-flow siblings not to collapse?

I have tried overflow:hidden, clear:both, border:1px solid white both on the element and generating an element before, nothing works.

Here's the example. H2's are removed from the flow to look pretty on the side, not collapsing, while H3 sits there collapsing with its predecessor no matter what. Now margin collapsing makes the vertical alignment of H2 and H3 in a coherent fashion, independent of the preceding element, impossible.

The constraint: HTML markup cannot be added, as the content is generated via Markdown.

Is this solvable?

Edit: In fact, the goal here was to make the h2 and their first h3 to come up at the same height.


Solution

  • One Solution

    In your particular case, it appears that you would not necessarily need to take h2 out of flow, and rather set it to position: relative, because it should achieve the effect you want.

    However, that does not really solve your question of margin collapse.

    Another Solution

    If you set the h3 that follows an h2 to display: inline-block, using...

    h2+h3 {display: inline-block;}
    

    ...then it resolves your collapsing issue, assuming you do not have inline elements immediately following the h3 tag. It appears that you plan on having any following text in a block level p tag, so that should not be an issue.