CSS 定位的绝对元素,父元素边界之外的自动宽度?
CSS Positioned Absolute Element, automatic width outside of parent's bounds?
因此,我将我的父元素定位为相对位置,以便让工具提示元素绝对定位在其内部的顶部。我知道您需要添加 "left: 0, right: 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 解决方案,谢谢!
我以前没见过这个问题,但我认为是 width: auto;
自动继承了其父项的属性。所以要么你必须在 (width: 50px;
) 或百分比 (width: 50%
) 中输入数字。
不要在 .tooltip
上同时设置 left
和 right
,设置 white-space: nowrap
应该可以:
.tooltip {
position: absolute;
top: 0;
left: 0;
margin: 0 auto;
text-align: center;
width: auto;
padding: 5px 10px;
white-space: nowrap;
}
您需要使用 this solution to center an absolute element. It does require an additional element, though. Demo
如果 .parent
可以内联,您可以将 .tooltip
呈现为 table,它会自动调整大小以适合其内容,但与使用 [=13 不同=], 它也支持 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;
}
我认为这个问题的最佳解决方案是不设置left
、right
或white-space: nowrap
,但我们有一个宽度属性 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;
}
因此,我将我的父元素定位为相对位置,以便让工具提示元素绝对定位在其内部的顶部。我知道您需要添加 "left: 0, right: 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 解决方案,谢谢!
我以前没见过这个问题,但我认为是 width: auto;
自动继承了其父项的属性。所以要么你必须在 (width: 50px;
) 或百分比 (width: 50%
) 中输入数字。
不要在 .tooltip
上同时设置 left
和 right
,设置 white-space: nowrap
应该可以:
.tooltip {
position: absolute;
top: 0;
left: 0;
margin: 0 auto;
text-align: center;
width: auto;
padding: 5px 10px;
white-space: nowrap;
}
您需要使用 this solution to center an absolute element. It does require an additional element, though. Demo
如果 .parent
可以内联,您可以将 .tooltip
呈现为 table,它会自动调整大小以适合其内容,但与使用 [=13 不同=], 它也支持 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;
}
我认为这个问题的最佳解决方案是不设置left
、right
或white-space: nowrap
,但我们有一个宽度属性 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;
}