0

Example jsfiddle: https://jsfiddle.net/ogf6ps39/1/

Given a template like:

<div class="outer">
  <div class="inner">
    hello world testing hello world
  </div>
</div>

Where the outer is position: absolute, how can I have the child container have a width based off its content.

So to something like:

example

Edit:

Just to add, the content of inner div is unknown and changes dynamically. So I cannot use fixed width or width percentages. It is also possible that the inner div can overflow the outer div

philip yoo
  • 2,462
  • 5
  • 22
  • 37

1 Answers1

2

I think this is not possible with CSS. See, your .inner element is div, which is a block element by default. This means it has 100% width of the parent by default. You can change the display of your .inner to inline-block for example to not have the 100% default width, but the problem is that there is a text inside. Once that text fills at least one row (one full width of the parent), and needs to wrap - from that moment the text is automatically considered to need the full width of the parent. And that is even if the text visually looks like it uses less width (it doesn't, it actually uses wull-width - it just wraps). You could see this point if you would take a look at a shorter text. I am providing an example with inline-block here:

.outer {
  max-width: 100px;
  max-height: 300px;
  min-height: 100px;
  background-color: yellow;
}

.inner {
  background-color: green;
  display: inline-block;
  margin-bottom: 10px;
}
<div class="outer">
  <div class="inner">
    hello world testing hello world
  </div>
  <div class="inner">
    hello
  </div>
  <div class="inner">
    hello world
  </div>
</div>

One thing I can assure you of in the meantime is that the absolute position on the parent element does not affect this in any way at all.

ajobi
  • 2,996
  • 3
  • 13
  • 28
  • Thank you for the explanation, I see what you mean there. So I'm guessing at this point, what I'd have to do is figure out line breaks with javascript – philip yoo Mar 16 '20 at 18:02
  • 1
    yes, it would be possible with javascript BUT, I would first try to re-think your use case, and try to find a different way to achieve what you want. Maybe you can avoid javascript and still display your information in a meaningful way. – ajobi Mar 16 '20 at 18:06
  • Also, if these texts will be of any bigger length, you can imagine that sooner or later there will appear a line of text which will indeed even visually look like it is full-width. That means your problem would not exist anymore. – ajobi Mar 16 '20 at 18:09