CSS定位绝对元素,自动宽度超出父界限?

时间:2015-05-06 20:29:08

标签: html css css3 position

所以,我将我的父元素定位为相对,以便允许工具提示元素在其顶部位于绝对内部。我知道你需要添加" left:0,right:0",这样元素的宽度仍然可以设置为auto,我已经完成了。但是,我的父元素有一个固定的宽度,工具提示被限制,所以自动宽度不能超出它,有没有办法解决这个问题?

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解决方案,谢谢!

4 个答案:

答案 0 :(得分:54)

未在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;
}

Working example

您需要使用 this solution 来居中绝对元素。但它确实需要一个额外的元素。的 Demo

答案 1 :(得分:3)

如果.parent可以内嵌,您可以将.tooltip呈现为一个表,它会自动调整以适应其内容,但与使用white-space:nowrap不同,它也会支持max-width

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

.tooltip {
  position: absolute;
  display: table;
  top: 0;
  left: 0;
  text-align: center;
  padding: 5px 10px;
  max-width: 200px;
}

答案 2 :(得分:2)

我相信,针对此问题的最佳解决方案不是设置leftrightwhite-space: nowrap,而是为width属性max-content添加了一个新值...添加width: max-content;(这也可以和max-width一起使用)

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

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

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

 width: max-content;
}

答案 3 :(得分:1)

我之前没有看到过这个问题,但我认为,width: auto;会自动继承其父级的属性。因此,您必须在(width: 50px;)或百分比(width: 50%)中输入数字。