我在一个相对定位的容器中有一个绝对定位的文本块。绝对定位的元素超出了它的容器的右边界。
问题是:文本未按正常方式换行;它过早地中断,而不是扩展到其定义的max-width
:
观察行为:
期望行为
HTML/CSS(JSFIDDLE: http://jsfiddle.net/WmcjM/):
<style>
.container {
position: relative;
width: 300px;
background: #ccc;
height: 100px;
}
.text {
position: absolute;
max-width: 150px;
left: 290px;
top: 10px;
background: lightblue;
}
</style>
<div class="container">
<div class="text">Lorem ipsum dolor sit amet</div>
</div>
注意:有几个变化似乎可以实现所需的行为,但并不是我想要的,包括:
- 在
.text
上定义min-width: 150px
(文本可能只是一个单词,我不希望容器过大) - 定位
.text
.相对于文档,而不是.container
(它需要出现在容器旁边,即使在浏览器调整大小时)
5条答案
按热度按时间jexiocij1#
尝试在.text上使用
position: relative;
编辑:也把它放在一个绝对定位的 Package 与您的自定义最大宽度
中央支助组
和HTML:
r6hnlfcb2#
尝试使用以下方法之一:
方法一:
transform: translate(x, y);
代替position: absolute; left: x; top: y;
方法2:
width: max-content;
详情请阅读此答案。o2g1uqev3#
将绝对位置更改为相对位置,并将.text换行到绝对位置的元素中。
http://jsfiddle.net/WmcjM/4/
pbpqsu0x4#
这里有一个策略,你可以使用,应该在Chrome,FF,Safari和IE11中工作,当我最后测试它时。
基本上,这个想法是欺骗浏览器认为你有宽度。前面的答案很好,但是如果你缩小父容器的宽度,你会注意到你的内容在达到父容器的宽度时开始换行。所以解决这个问题的想法是使用另一个容器,它位于你想要锚内容的位置,然后将你的内容与那个东西相关联。
不同的是,我们将使用第一个容器来设置我们想要的最大宽度。由于该容器的高度为0,因此您甚至看不到它。
JSF中间文件:http://jsfiddle.net/WmcjM/252/
超文本标记语言
中央支助组
一个二个一个一个
h43kikqp5#
将
max-width
与width: max-content
以及white-space: pre-wrap
一起使用,可以得到理想的结果,而无需使用相对定位或换行。设置如下: