1

I have a dynamic container. It contains a paragraph, and some other elements.

<div id="container" style="border: 2px solid black; position: absolute; display: flex; flex-direction: column; width: auto">
  <p>This is a long description. It is very long. It has many sentences. There are details contained within.</p>
  <p>Short p</p>
  <input type="number" style="width:200px" />
  <button style="width: 50px">OK</button>
</div>

Note that the container becomes widened severely by the long paragraph. This is not desired. I would like the container to be sized based on the children not including the paragraph. So I'd like to have the container width constrained by the default numeric input field width, or the button, whichever is wider. Note if the first paragraph tag is removed then it looks the way I want, as that 2nd short p does not exceed the width of the input.

I'm actually a web developer by trade and have been doing this for 10 years. This is one of the few remaining snags with CSS now that we already seemingly have a world of nice things with flex, grid, etc. available to us today. But it's these chicken-egg type problems that continue to frustrate, and I can't even find a way to properly google solutions to this problem.

What is the approach here? Do I try to hack the paragraph to take the width of a sibling? Why does it not work if I set width: 100% on the offending non-wrapping paragraph?

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • `width: 0; min-width: 100%;` to p – Temani Afif Dec 03 '20 at 00:07
  • @TemaniAfif Holy cow, you learn something new every day. Very useful. – somethinghere Dec 03 '20 at 00:08
  • What is this sorcery? Thanks, but I worry the code has poor understandability. Not something CSS is strong at in general, though. I'd urge you to provide an answer rather than close as dupe so I can give you points, but you don't really need more points, do ya? – Steven Lu Dec 03 '20 at 00:09
  • as I described in the duplicate, width:0 will make the element to not contribute to the container width then min-width will re-consider the container width to define the element width – Temani Afif Dec 03 '20 at 00:13
  • simply upvote the duplicate would be enough ;) [I don't need more points but it would be useful to the community to upvote *helpful* answers] – Temani Afif Dec 03 '20 at 00:14
  • Yep. I was bracing myself for answers calling for javascript or fixed width on the container. In my usecase it is a Popper element. – Steven Lu Dec 03 '20 at 00:15

0 Answers0