0

I feel like I'm losing my mind...

span {
  max-width: 150px;
  display: inline-block;
  background: yellow
}
<span>words words words words words words words words </span>

What I want: The yellow box to be no wider than the longest line of text.

What I get: Lots of empty space on the right hand side.

A few years ago I could have believed this was a limitation of CSS. But it's 2023, things are supposed to be good these days...

I've tried everything I can think of, floats, tables, flex, grid, obscure property values like fit-content etc.

I THINK I'm coming to the conclusion that this isn't possible without javascript?

Can someone confirm? Can someone explain WHY?

Or am I missing something simple?

Thank you!

cloned
  • 6,346
  • 4
  • 26
  • 38
Codemonkey
  • 4,455
  • 5
  • 44
  • 76

1 Answers1

2

I think you're looking for box-decoration-break: clone. Make sure that your element is set to display: inline and use a wrapping container to control the width.

.container {
  max-width: 15rem;
}

span {
  display: inline;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;


  /* Just for  purposes */
  font-family: "Helvetica Neue", Helvetica, Arial, "sans-serif";
  font-size: 3rem;
  color: hsl(0 0% 100% / 1);
  line-height: 1.2;
  text-transform: uppercase;
  background: darkviolet;
  padding: .5rem 1rem;
}
<div class="container">
  <span>different words with different lengths to make it interesting</span>
</div>
jme11
  • 17,134
  • 2
  • 38
  • 48