2

Firstly, apologies for the hard to understand question title.

In HTML/CSS, I want my multiple line text element to inherit it's width from the text inside. It does this if the contained text only spans one line, but when the text spans multiple lines, it forces itself to width:100%;.

Here's a fiddle of the problem: https://jsfiddle.net/guzvpe2q/

This is what happens: enter image description here

This is what should happen: enter image description here

Thanks in advance.

rorymorris89
  • 1,144
  • 7
  • 14
  • Related - http://stackoverflow.com/questions/34995740/css-when-inline-block-elements-line-break-parent-wrapper-does-not-fit-new-width – Paulie_D Sep 21 '16 at 16:20
  • @Paulie_D thanks, I guess I'll have to apply a JS fix then (you are right, this applies to floats, flex and everything else it seems). – rorymorris89 Sep 21 '16 at 16:27

1 Answers1

0

The div really is being pushed that wide by the text, but the text cannot fit so it needs to be pushed down a line.

You also need display:inline-block.

One way around it would be to add manual line-breaks after the first word (not exactly ideal i know)

See (https://www.w3.org/TR/CSS21/visudet.html#inlineblock-width)

Stuart
  • 6,630
  • 2
  • 24
  • 40
  • That's the thing, if I put `span` tags around each word and apply `inline-block` to both the container and the spans, the problem still occurs. So really, it *isn't* being pushed that wide, but the browser treats it like it is. See this: https://jsfiddle.net/guzvpe2q/2/ – rorymorris89 Sep 21 '16 at 16:16
  • It's when the computed width needed is longer than the containing element (the element that your h1 sits in) it will /seem/ like its 100% wide but its not -- try expanding the width of the jsfiddle window to see what i mean (if you dont already) --- Does this help: https://jsfiddle.net/guzvpe2q/3/ – Stuart Sep 21 '16 at 16:18
  • Yeah I fully understand what you mean. I can easily fix this by doing calculations in JavaScript and applying a width to the container `h1` - but should I really need JS for this? – rorymorris89 Sep 21 '16 at 16:20
  • Indeed, i was going to suggest a JS fix for this, it seems its an oddity really all depending on the viewport / outer container width, as the text still needs to take up its space, but you'd think it would be recalculated when lines wrap eh... – Stuart Sep 21 '16 at 16:22
  • It seems like my only option. Cheers for helping anyway. – rorymorris89 Sep 21 '16 at 16:26