Michael Lewis
Michael Lewis

Reputation: 4302

How to get minimal width behavior (such as when floating or pos: abs) without using a float or pos: abs

Let's say I have a block element, such as an h2:

<h2>Title</h2>

And I give it a background color. The background will span the entire width of the wrapper (as it should).

If I float it, or position: absolute, it will 'shrink wrap' the words. However, both of these methods take the element out of the 'flow' and prevent it from pushing the rest of the content down the page.

I'd like to avoid having to add a clear underneath the title every time. Is there a better solution? I thought the overflow property could do it, but I'm not figuring it out.

fiddle:

http://jsfiddle.net/QxRRh/

Upvotes: 0

Views: 85

Answers (2)

Dominic Alie
Dominic Alie

Reputation: 213

Wrap the header text in a <span> and apply the background color to that span.

HTML:

<h2><span class="blue">Title</span></h2>

CSS:

.blue{ background-color:blue; }

Upvotes: 0

Turnip
Turnip

Reputation: 36662

Here's one (very simple) way ...

h2 {
    display: table;
}

Fiddle

Upvotes: 2

Related Questions