Container does not shrink when inner text wraps

256 Views Asked by At

I am trying to have two elements horizontally aligned where the one on the left has text that may wrap then sizing the screen, and the one on the right allows for no wrapping. When the content wraps, the first element maintains the width of content + (wrapped word - pixels causing wrapping), instead of shrinking to fit the content.

I created an example on Fiddle where you can see the grey background of the first element having no content for a couple of pixels, instead of resizing to only include the text.

.container {
  display: flex;
  width: 760px;
}

.item {
  background-color: grey;
  width: fit-content;
  block-size: fit-content;
}

.item2 {
  background-color: green;
  white-space: nowrap;
  align-self: flex-start;
}
<div class="container">
  <div class="item"><span> This Text to auto-adjust to only fit the content when wrapping</span></div>
  <div class="item2">This should be right next to last word on first line on the left</div>
</div>

JSFiddle Demo

Is there a way of achieving an auto-size to only fit-content on resizing of the screen so the 2 element stays as close to the text of the first one as possible?

1

There are 1 best solutions below

2
Ruochen Jia On

Elements inside a flexbox has flex-grow and flex-shrink set by default, which allows them to bypass the basic width and height properties.

To solve this problem, just disable flex-grow and flex-shrink:

.item {
    background-color: grey;
    width: fit-content;
    block-size: fit-content;
    flex-grow: 0;
    flex-shrink: 0;
}