Search code examples
htmlcsscss-positionword-wrap

Preserve normal word wrapping inside absolutely positioned container


I have an absolutely positioned block of text inside a relatively positioned container. The absolutely positioned element exceeds the right boundary of its container.

The problem is: the text isn't wrapping as normal; it's breaking prematurely rather than expanding to its defined max-width:

Observed behavior:

enter image description here

Desired behavior

enter image description here

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>

Note: A couple changes that appear to achieve the desired behavior, but which aren't quite what I'm looking for, include:

  • defining min-width: 150px on .text (the text might just be one word, and I don't want the container to be oversized)
  • positioning .text. relative to document, rather than to .container (it needs to appear beside the container, even when the browser is resized)

Solution

  • Try using position: relative; on .text

    EDIT: Also put it inside an absolute positioned wrapper with your custom max-width

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

    And 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>