Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set div to the width of its containing text?

Tags:

html

css

width

I have a div class heading that contains dynamically generated text, and I want to underline it using a border-bottom. But if I set .heading {width:auto} then the div horizontally fills its container, and the underline is way too long.

How can I make the div be only as long as the containing text?

http://jsfiddle.net/roLxsw3v/

like image 741
Joe Morano Avatar asked Feb 23 '15 00:02

Joe Morano


1 Answers

Visual formatting model - 'Inline-block', non-replaced elements in normal flow:

If width is auto, the used value is the shrink-to-fit width as for floating elements.

A computed value of auto for margin-left or margin-right becomes a used value of 0.

Therefore you could change the display of the element to inline-block.

In doing so, the element's width will "shrink to fit" its contents, in this case the text.

Updated Example

.heading {
    background: blue;
    display: inline-block;
}
<div class="heading">text</div>

It's also worth pointing out that you can omit width: auto since auto is already the default value.

Clearly, you could also change the element's type from a div to a span, which is inline by default.

like image 194
Josh Crozier Avatar answered Nov 15 '22 05:11

Josh Crozier