1

I have a container that effectively, I want to compress the contents to their minimum width without scroll bars. fit-content is close, but allows the content to use more width than it actually needs. I could also explicitly set the container's width, but that requires me to know the min-width of the contents ahead of time.

So in the example below, the box width should default to compressing the inner item to 3 lines. How can the box reclaim this bit of space?

.box {
  background-color: green;
  resize: both;
  overflow: auto;
  padding: 1em;
  min-width: 2em;
  width: fit-content;
  height: 10em;
}

.el {
  background-color: teal;
  width: 100%;
  min-width: 5em;
}
<div class="box">
  <div class="el">
    Lorem isa psalm ipsom
  </div>
</div>
Tezra
  • 8,463
  • 3
  • 31
  • 68
  • This can get messy, when you say as small as possible what do you mean? Just because it is compressed in to three lines doesn't make it smaller than when it isn't, at least in terms pixels. – Libra Feb 05 '20 at 19:39

2 Answers2

3

I think what you are looking for is the min-content width value:

.box {
  background-color: green;
  padding: 1em;
  min-width: 2em;
  width: min-content;
  height: 10em;
}

.el {
  background-color: teal;
}
<div class="box">
  <div class="el">
    Lorem isa psalm ipsom
  </div>
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/width#min-content

ajobi
  • 2,996
  • 3
  • 13
  • 28
1

You can simply do this by using the CSS width rule.

<style>
.box {
    background-color: green;
    width: max-content;
}
.el {
    background-color: teal;
    width: max-content;
}
</style>

In case you want the content to be fit with exactly the width of the word, change the width to min-content

<style>
.box {
    background-color: green;
    width: max-content;
}
.el {
    background-color: teal;
    width: min-content;
}
</style>

Hope that solves your problem..

Nithin Suresh
  • 360
  • 1
  • 7