在绝对定位的元素上遇到nowrap和max-width问题

Roh*_*hit 11 css css-position tooltip css3 word-wrap

我猜这两个属性实际上并没有合作,但我的情况是:

我正在尝试创建一个工具提示组件.我的工具提示绝对定位,因为我不知道内容的长度是多少,没有宽度.因此,与宽度相关的CSS,文本只是形成一个高,瘦的列.我试过了max-width,但就它本身而言,它什么也没做.所以我决定尝试white-space: nowrap,虽然它很好地不包装文本,但它似乎也没有以有用的方式遵循最大宽度,而文本反而超出了元素的边界.

如果有一个干净的解决方案,我想不出如何解决我的问题.我希望有一个绝对定位的div扩展到适合它的内容,直到最大值,此时它包装.我看到的一个建议是将元素设置为弹性框,但据我所知,这对于IE来说不是很好,所以我认为在我的情况下是不可行的.有什么建议?

.wrapper {
  position: relative;
  display: inline;
}

.info {
  position: absolute;
  bottom: 1.2em;
  left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
  <span>[ ? ]</span>
  <div class="info">Any long text can go in here to test what goes wrong with wrapping.</div>
</div>
Run Code Online (Sandbox Code Playgroud)

jfe*_*man 6

避免使用,white-space:nowrap因为这会将您的文本限制为一行。max-width应该与显示绝对但不在行内元素内的块级元素一起使用。为了解决这个问题,我将工具提示放在包装块之外,并使用 javascript 将其定位在鼠标位置。

这是针对您的问题的简单解决方案。单击“打开工具提示”以显示工具提示并移动滑块以更改 的值max-width

showContext = function() {
    var e = window.event;

    var posX = e.clientX;
    var posY = e.clientY;
    var info = document.getElementById("info");
    info.style.top = posY + "px";
    info.style.left = posX + "px";
    info.style.display = "block";
}

changeWidth = function(value) {
		var info = document.getElementById("info");
    info.style.maxWidth = value + "px";
}
Run Code Online (Sandbox Code Playgroud)
.wrapper {
    position: relative;
}

.info {
    position: absolute;
    max-width:300px;
    display:none;
    border:1px solid black;
    background-color:white;
}

.range {
  margin:10px 0px 10px 0px;
  display:block;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
    max-width slider
    <input id="range" class="range" type="range" min="100" max="600" oninput="changeWidth(this.value)"/>
    <input type="button" value="open tooltip" onclick="javascript:showContext();" />
</div>
<div id="info" class="info">Any long text can go in here to test what goes wrong with wrapping.</div>
Run Code Online (Sandbox Code Playgroud)


Ovi*_*uru 2

添加一个min-width:100%和一个white-space: nowrap;

.wrapper {
  position: relative;
  display: inline;
}
 
.info {
  position: absolute;
  min-width: 100%;
  white-space: nowrap;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
    <span>[ ? ]</span>
    <div class="info">Any long text can go in here to test what goes wrong with wrapping.</div>
</div>
Run Code Online (Sandbox Code Playgroud)