CSS Positioned Absolute Element,父边界之外的自动宽度?

新手上路,请多包涵

因此,我将我的父元素定位为相对位置,以便让工具提示元素绝对定位在其内部,位于其顶部。我知道您需要添加“左:0,右:0”,这样元素的宽度仍然可以设置为自动,我已经这样做了。但是,我的父元素有一个固定的宽度,工具提示被限制到这个宽度,所以自动宽度不能超出它,有什么办法解决这个问题吗?

CSS:

 .parent {
  position: relative;
  width: 100px;
  height: 100px;
}

.tooltip {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  text-align: center;
  width: auto;
  padding: 5px 10px;
}

要素:

 <div class="parent">
  <div class="tooltip">Text goes here</div>
</div>

没有 JS,请寻找 CSS 解决方案,谢谢!

原文由 Danny 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
2 个回答

不能同时设置 left right .tooltip white-space: nowrap

 .tooltip {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0 auto;
  text-align: center;
  width: auto;
  padding: 5px 10px;
  white-space: nowrap;
}

工作示例

您需要使用 此解决方案 来使绝对元素居中。不过,它确实需要一个额外的元素。 演示

原文由 Honore Doktorr 发布,翻译遵循 CC BY-SA 3.0 许可协议

I believe the best solution for this issue is not setting left , right or white-space: nowrap but we have a new value for width property max-content …所以只需添加 width: max-content; (这个也适用于 max-width

演示:http: //jsfiddle.net/qLgw8bxu/

支持: https ://caniuse.com/#search=max-content

 .tooltip {
 background-color: blue;
 position: absolute;
 text-align: center;
 padding: 5px 10px;

 width: max-content;
}

原文由 Joe Koker 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题