Search code examples
csswidthword-wrap

How can I adjust the width of the inner element so that it word wraps naturally?


In the example below, I would like word wrap only to happen if the left side of position-me hits the left side of the screen like this.

I think that currently #position-me inherits the width of the parent element and even if I set width: auto !important; in #position-me it still wraps at the parent width.

If I set white-space: nowrap; on #position-me then it overrides the 100px width, but the text overruns the div (and the page potentially!)

#wrapper {
  position: absolute;
  bottom:0;
  right:0;
  width: auto;
  height: 100px;
  background-color: red;
}

#position-me {  
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(-100%, -100%);
  width: auto;
  height: auto;
  background: green;
}
<div id='wrapper'>
This is the wrapper div
    <div id='position-me'>
        Text is here and it is great, I wonder when it will decide to wrap itself?
    </div>  
</div>
 

https://jsfiddle.net/pfa89bu1/2/


Solution

  • Use a big negative margin left, limit the width to the width of the screen minus the red box width and use bottom/right for the position:

    #wrapper {
      position: absolute;
      bottom: 0;
      right: 0;
      height: 100px;
      background-color: red;
    }
    
    #position-me {
      position: absolute;
      bottom: 100%;
      right: 100%;
      margin-left: -200vmax;
      max-width: calc(100vw - 100%);
      background: green;
    }
    <div id='wrapper'>
      This is the wrapper div
      <div id='position-me'>
        Text is here and it is great, I wonder when it will decide to wrap itself?
      </div>
    </div>