-1

The overlay text takes up the full width of its container when there is a word break. I only want it to take up the width of the actual text. Is this possible?

See problem in codepen.

HTML

<div class="container">
  <div class="overlay">
    <p class="centered-overlay-text">Not Good</p>
  </div>
</div>
<div class="container">
  <div class="overlay">
    <p class="centered-overlay-text">Good</p>
  </div>
</div>

CSS

.container {
  position: relative;
  width: 60px;
  height: 60px;
  background-color: yellow;
  margin-bottom: 10px;
}

.overlay {
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.centered-overlay-text {
  text-align: center;
  background-color: blue;
}

codepen

https://codepen.io/anon/pen/MVpLKz

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    you cannot ... and the logic is the opposite of what you think, the p grows and when it reach the full width the work break ... so the full width is there before the breaking word – Temani Afif Mar 28 '18 at 08:48
  • add a `
    ` betwen *not* and *good* and see what happen ... in this case you have the word break before thus the width is ok ;)
    – Temani Afif Mar 28 '18 at 08:49
  • since you have static values for width on the `container` why not just add them to `centered-overlay-text` I tested `width:40px;` and it worked nicely. – mcv Mar 28 '18 at 09:09
  • As temani says - if your word wraps, that means it has made the container reach 100% width so the only way to do this would be to use some js to measure each word (or each line) and the resize the div manually or put a br after each word – Pete Mar 28 '18 at 09:27

2 Answers2

1

Try adding width: min-content; to centered-overlay-text

Like so

As mentioned in the comment though, this isn't fully cross-browser.

wickywills
  • 4,024
  • 2
  • 38
  • 54
-1

Like this ?

.container {
  display: flex;
  justify-content: center;
  width: 60px;
  height: 60px;
  background-color: yellow;
}

.centered-overlay-text {
  text-align: center;
  background-color: blue;
  align-self: center;
  color: white;
}
<div class="container">
    <p class="centered-overlay-text">Hell<br>Yeah !</p>
</div>
FloJDM
  • 328
  • 3
  • 12