【问题标题】:Width of absolutely positioned element绝对定位元素的宽度
【发布时间】:2020-02-22 20:27:05
【问题描述】:

我已经绝对定位了 div 元素 (.tooltip) 和另一个 div (.text),其中包含文本(设置了 max-width)。当.tooltipleft 属性足够大时,它的宽度会缩小(我猜是因为right 属性的默认值为0)。我想要的是.tooltip 首先尊重.text 的宽度(它的内容)。我尝试过的:

  1. tooltip 的宽度设置为fit-content - 这基本上是我想要实现的(在 sn-p 上显示)但它在 IE 上不起作用(我必须支持)。没有.tooltip 的宽度会缩小。

  2. 设置tooltiptext 的固定宽度 - 也不可能,因为text div 中的文本可能很短,然后会有空白空间。

  3. 另一方面,文本可能很长,所以我无法像类似问题中建议的那样设置white-space: nowrap

.tooltip {
  position: absolute;
  border: 1px solid red;
  left: 400px;
  width: fit-content;
}

.text {
  max-width: 200px;
}
<div style="border: 1px solid green;width:500px; height: 500px; position:relative">
  <div class="tooltip">
      <div class="text">test test test test test test test test test</div>
    </div>
</div>

【问题讨论】:

  • 寻求代码帮助的问题必须包括在问题本身中重现它所需的最短代码,最好是在堆栈片段中。尽管您提供了一个链接,但如果它变得无效,那么您的问题对于未来遇到同样问题的其他 SO 用户将毫无价值。见Something in my website/example doesn't work can I just paste a link
  • 一个示例代码或一个可视化插图(例如铅笔划痕)更容易获得帮助
  • 这是一种解决方案:jsfiddle.net/yrbsdakp 将在问题重新打开时发布
  • @TemaniAfif 谢谢,这有点解决了我描述的问题(我会接受它),但是我已经将转换用于动画目的,您是否看到您的解决方案的其他替代方案?
  • 用另一种方法添加了答案;)

标签: javascript html css


【解决方案1】:

想法是用翻译替换left

.tooltip {
  position: absolute;
  border: 1px solid red;
  left: 0;
  transform:translateX(400px);
}

.text {
  max-width: 200px;
}
<div style="border: 1px solid green;width:500px; height: 500px; position:relative">
  <div class="tooltip">
      <div class="text">test test test test test test test test test</div>
    </div>
</div>

如果你想继续使用left,考虑一些负边距给元素更多空间:

.tooltip {
  position: absolute;
  border: 1px solid red;
  left: 400px;
  margin-right:-400px; /* Make it bigger enough, at least the same as left */
}

.text {
  max-width: 200px;
}
<div style="border: 1px solid green;width:500px; height: 500px; position:relative">
  <div class="tooltip">
      <div class="text">test test test test test test test test test</div>
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2022-01-26
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多