在绝对定位的容器内保留正常的自动换行

Emm*_*ett 22 html css css-position word-wrap

我在相对定位的容器内有一个绝对定位的文本块.绝对定位的元素超出其容器的右边界.

问题是:文本没有正常包装; 它过早地破裂而不是扩展到它定义的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>
Run Code Online (Sandbox Code Playgroud)

注意:一些看起来可以实现所需行为的更改,但这些并不是我想要的,包括:

  • 定义min-width: 150pxon .text(文本可能只是一个单词,我不希望容器超大)
  • 定位.text.相对于文档,而不是.container(它需要出现在容器旁边,即使浏览器调整大小)

Bog*_*bak 12

尝试使用position: relative;.text

编辑:也将它放在一个绝对定位的包装器中,你的自定义最大宽度

CSS

.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;
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


kyl*_*yth 6

将绝对位置更改为relative,并将.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;
}
Run Code Online (Sandbox Code Playgroud)


Ed *_*sky 6

尝试使用以下方法之一:

方法一: transform: translate(x, y);代替position: absolute; left: x; top: y;

方法 2: width: max-content;有关详细信息,请阅读此答案