How do I shrink-wrap H1?

I want to add an SVG background to my H1 elements to act as a wavy underline. The problem is, I want this SVG to stretch to the width of the text within the H1 element. As we know, by default, all headings are block elements so they stretch to 100% width. Is there anyway to make them behave like “inline-block”, whilst preventing other inline elements from positioning themselves next to the heading. In other words, is there a way I can shrink-wrap a heading, whilst still ensuring it’s the only element on that line?

I’m going to a have quick play with floats, but I’ll admit that floats have never solved any design problem for me. They always seem to introduce other undesirable side-effects so I’m not incredibly optimistic.

Cheers

Setting the H1 to “display: table;” seems to satisfy my requirements. I don’t particular care about IE6/IE7, so it’s an adequate solution.

Lol I just realized I don’t know be heart if float left - clear right or both will clear non floated items. Anyways… Try that first. If that doesn’t work you can give it a margin right of 100% (again not memorized - wow I’m on it). If that doesn’t work then you can give it a fixed dimension margin right. If that doesn’t work because fluid width you can put a “br” after it probably.

Float, inline-block, and position absolute or fixed will shrink wrap.

consider also :

h1{ display:inline-block; vertical-align: top; }

  • ie friendly
  • doesn’t cause any issues should you decide to use some AP /RP pseudo elements for further styling
  • is otherwise almost as good as float:left; clear:left;

I’ve also added markup for it: a span sandbag when I know I want to limit a background to the inline text rather than the block element.

Adding markup is not as nice as the other suggestions up here, but it is a viable option especially if you also need the block-box of the h1 element too (like full-width background-colors or borders, and then something limited to the text inside).