-1

I have run into this problem:

span {
  width: fit-content;
  background-color: yellow;
}

div {
  width: fit-content;
  border: black 1px solid;
  max-width: 100px;
}
<div>
  <span>Fooooo Barrrrrrrr</span>
</div>

<p>The right side border should be touching the right side of the longest line.</p>

I would like the div to be as close to the size of the span as possible. I have put width: fit-content; there but it seems to only fit to its own max-width. I am not asking to fit the div to the boundries of every line, but it should be as wide as the widest line in span. How can I resolve this?

Donald Zhu
  • 672
  • 4
  • 14

2 Answers2

-1

Here you can use min-content, or if you don't want the words to break you can use max-content only on the div and let the span have auto width (it's the default, so no need to explicitly set it). Note that your CSS will influence all divs on your page, so to test this you need to set unique classes or ids to not have the first css influence the second css.

span.span1 {
  width: fit-content;
  background-color: yellow;
}

div.div1 {
  width: min-content;
  border: black 1px solid;
  max-width: 100px;
}

span.span2 {
  background-color: yellow;
}

div.div2 {
  border: black 1px solid;
  width: max-content;
}
<div class="div1">
  <span class="span1">Fooooo Barrrrrrrr</span>
</div>
<br>
<div class="div2">
  <span class="span2">Foooooo Barrrrrrrrrr</span>
</div>
anatolhiman
  • 1,762
  • 2
  • 14
  • 23
  • This solution mostly works, but it tends to wrap my text prematurly (texts that don't exceed `max-width` will still wrap into two lines). How can I ensure that the text doesn't wrap if it still has space? – Donald Zhu Aug 26 '21 at 06:52
  • Updated the example. I think your first div css influenced your test, but I have now made it clearer that they need unique css that don't interfere with each other. – anatolhiman Aug 26 '21 at 07:12
-1

Try with this:

.customblk span {
    background-color: yellow;
}
.customblk div {
    border: black 1px solid;
    max-width: max-content;
}
<section class="customblk">
<div>
  <span>Fooooo Barrrrrrrr </span>
</div>
<p>The right side border should be touching the right side of the longest line.</p>
</section>
Urvisha
  • 45
  • 2