如何将跨度宽度强制为内部文本的长度?

时间:2018-07-12 15:25:34

标签: html css

我有一个图标,将鼠标悬停在该图标上时会显示工具提示框。我已经根据W3Schools CSS tooltip example对其进行了塑造。

代码如下:

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  /* I WANT THIS TO CHANGE BASED ON TEXT LENGTH */
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}
<body style="text-align:center;">

  <p>Move the mouse over the text below:</p>

  <div class="tooltip">Hover over me
    <span class="tooltiptext">Some fairly long tooltip text that should <br /> only display on two lines.</span>
  </div>
</body>

我的问题是,出现在工具提示中的文本是动态生成的,并且可能比Blur的静态120px宽度宽。我希望根据文本的宽度来调整Blurb的宽度,但是如果我将宽度设置为auto,则其宽度只能与第一个单词一样宽。如何更改宽度?

2 个答案:

答案 0 :(得分:1)

只需设置var bobMock = new Moq.Mock<IEmployee>(); bobMock.Setup(x => x.IsWorkingOnDate()) .Returns(value); bobMock.Setup(x => x.SendNotificationPreference()); 而不是在white-space: nowrap;上设置宽度

.tooltip .tooltiptext
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  white-space: nowrap; /* this is new */
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  /* Position the tooltip */
  position: absolute;
  z-index: 1;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
}

答案 1 :(得分:0)

以下内容将至少保持120px宽的工具提示,并防止文本自动换行(<br>标签将用于换行符)。如果消息太长,它也会破裂/看起来难看。

<!DOCTYPE html>
<html>
<style>
.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
    visibility: hidden;
    min-width: 120px; /* min-width makes sure it will always be at least 120px */
    white-space: nowrap; /* Prevents text from wrapping on its own */
    background-color: black;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px 0;

    /* Position the tooltip */
    position: absolute;
    z-index: 1;
}

.tooltip:hover .tooltiptext {
    visibility: visible;
}
</style>
<body style="text-align:center;">

<p>Move the mouse over the text below:</p>

<div class="tooltip">Hover over me
    <span class="tooltiptext">Some fairly long tooltip text that should <br /> only display on two lines.</span>
</div>

</body>
</html>