【问题标题】:CSS: Position absolute tooltip width auto text breaks on new lineCSS:定位绝对工具提示宽度自动文本换行符
【发布时间】:2022-08-18 18:12:08
【问题描述】:

我创建了一个具有绝对位置的工具提示,并且我没有指定任何最小或最大宽度(所以 with 应该是汽车,根据它的内容进行拉伸),但工具提示中的文本——可以舒适地放在一行上——由于某种我不明白的原因,换行了。

See my jsfiddle 和我的代码如下:

.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 class=\"tooltip-wrapper\">
  <span class=\"tooltip\">Lorem ipsum dolor sit amet</span>
  Text
</div>

谁能解释我为什么会这样? 无论如何我可以让文本保持在一行而不使用white-space: nowrap,然后在它到达max-width时换行?

谢谢!

  • 它是左边:50% 在宽度处阻塞元素:50%

标签: html css


【解决方案1】:

不要使用左/平移居中。做不同的事情:

.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 class="tooltip-wrapper">
  <span class="tooltip">Lorem ipsum dolor sit amet</span>
  Text
</div>

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多