Home > Software design >  CSS: Position absolute tooltip width auto text breaks on new line
CSS: Position absolute tooltip width auto text breaks on new line

Time:08-18

I created a tooltip with absolute position and I'm not specifying any min nor max width (so the with should be auto, stretching according to it's content), yet the text inside the tooltip - which could comfortably sit on one single line - for some reason I don't understand, breaks on a new line.

See my jsfiddle and my code below:

.tooltip-wrapper {
  width: 250px;
  position: relative;
  font-size: 14px;
  border: 1px solid;
  padding: 10px;
  text-align: center;
  margin: 10px auto;
}

.tooltip-wrapper:hover .tooltip {
  display: block;
}

.tooltip {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.5);
  padding: 3px;
  color: #fff;
  font-size: 12px;
  display: none;
}
<div >
  <span >Lorem ipsum dolor sit amet</span>
  Text
</div>

Can anyone explain me why this happens? And is there anyway I can let the text stay on one line without using white-space: nowrap, and then wrap if it reaches a max-width for example?

Thank you!

CodePudding user response:

Don't center using left/translate. Do it differently:

.tooltip-wrapper {
  width: 250px;
  position: relative;
  font-size: 14px;
  border: 1px solid;
  padding: 10px;
  text-align: center;
  margin: 10px auto;
}

.tooltip-wrapper:hover .tooltip {
  display: block;
}

.tooltip {
  position: absolute;
  /* added */
  inset: 0 0 auto; /* top, left and right equal to 0 */
  margin: auto;
  width: fit-content;
  /* */
  background: rgba(0, 0, 0, 0.5);
  padding: 3px;
  color: #fff;
  font-size: 12px;
  display: none;
}
<div >
  <span >Lorem ipsum dolor sit amet</span>
  Text
</div>

  • Related