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/
Visual formatting model - 'Inline-block', non-replaced elements in normal flow:
If
widthisauto, the used value is the shrink-to-fit width as for floating elements.A computed value of
autoformargin-leftormargin-rightbecomes a used value of0.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With