css 在绝对定位的容器内保持正常的文字 Package

m528fe3b  于 2023-03-25  发布在  其他
关注(0)|答案(5)|浏览(140)

我在一个相对定位的容器中有一个绝对定位的文本块。绝对定位的元素超出了它的容器的右边界。
问题是:文本未按正常方式换行;它过早地中断,而不是扩展到其定义的max-width

观察行为:

期望行为

HTML/CSSJSFIDDLE: 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(它需要出现在容器旁边,即使在浏览器调整大小时)
jexiocij

jexiocij1#

尝试在.text上使用position: relative;
编辑:也把它放在一个绝对定位的 Package 与您的自定义最大宽度

中央支助组

.container {
    position: relative;
    width: 300px;
    background: #ccc;
    height: 300px;
}

.wrap_text {
    position: absolute;
    max-width: 200px;
    top: 10px;
}

.text {
    position: relative;
    left: 290px;
    background: lightblue;
}

HTML

<div class="container">
    <div class="wrap_text">
        <div class="text">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
        </div>
    </div>
</div>
r6hnlfcb

r6hnlfcb2#

尝试使用以下方法之一:

方法一:transform: translate(x, y);代替position: absolute; left: x; top: y;
方法2:width: max-content;详情请阅读此答案。

o2g1uqev

o2g1uqev3#

将绝对位置更改为相对位置,并将.text换行到绝对位置的元素中。
http://jsfiddle.net/WmcjM/4/

.container {
    position: relative;
    width: 300px;
    background: #ccc;
    height: 300px;
}

.text {
    position: relative;
    /*min-width: 200px;*/
    left: 290px;
    background: lightblue;
}

.wrap {
    position: absolute;
    max-width: 200px;
    top: 10px;
}
pbpqsu0x

pbpqsu0x4#

这里有一个策略,你可以使用,应该在Chrome,FF,Safari和IE11中工作,当我最后测试它时。
基本上,这个想法是欺骗浏览器认为你有宽度。前面的答案很好,但是如果你缩小父容器的宽度,你会注意到你的内容在达到父容器的宽度时开始换行。所以解决这个问题的想法是使用另一个容器,它位于你想要锚内容的位置,然后将你的内容与那个东西相关联。
不同的是,我们将使用第一个容器来设置我们想要的最大宽度。由于该容器的高度为0,因此您甚至看不到它。
JSF中间文件:http://jsfiddle.net/WmcjM/252/

超文本标记语言

<div class="container">
  <div class="sizing-container">
      <div class="your-text">You can put whatever you want here and you can see that the content wraps when you hit your max-width, but that max-width is actually defined as the width of the sizing container</div>
  </div>
</div>

中央支助组

.container {
    position: relative;
    background: #ccc;
    width: 70px;
    height: 70px;
    margin-bottom: 100px;
}

.your-text {
    position: absolute;
    left: 0;
    top: 100%;
    background: lightblue;
    word-break: break-word;
}

.sizing-container {
    position: absolute;
    display: block;
    height: 0px;
    background: red;
    width: 200px; // This is your max-width!
    top: 16px;
    left: 100%;
}

一个二个一个一个

h43kikqp

h43kikqp5#

max-widthwidth: max-content以及white-space: pre-wrap一起使用,可以得到理想的结果,而无需使用相对定位或换行。
设置如下:

width: max-content;
max-width: 30ch;
white-space: pre-wrap

相关问题