Search code examples
htmlcssoverflowword-wrap

CSS text-overflow: ellipsis wrapping on nested div structure


I have the following 3-level tree of nested divs. The outer one has a max width and I want the ellipsis wrapping on that node, not on the individual child nodes.

I already almost got there, problem is that (depending on the outer width) the inner nodes aren't cut to fit as much text as possible inside the parent node. Instead only as many child nodes are shown as would fit completely, the rest is just blank space. So instead of

left1~right1 left2~right2…

I would rather like

left1~right1 left2~right2 left3~rig…

To see this effect, you may have to adjust the value of max-width.

html, body {
  width: 100%;
}

.outer {
  background-color: lavender;
  display: inline-block;
  max-width: 30%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.inner {
  display: inline-block;
}

.inner>* {
  display: inline;
}

.inner>:first-child::after {
  content: "~"
}
<html>

  <body>
    <div class="outer">
      <div class="inner">
        <div>left1</div>
        <div>right1</div>
      </div>
      <div class="inner">
        <div>left2</div>
        <div>right2</div>
      </div>
      <div class="inner">
        <div>left3</div>
        <div>right3</div>
      </div>
      <div class="inner">
        <div>left4</div>
        <div>right4</div>
      </div>
    </div>
  </body>

</html>


Solution

  • You are very close to your expected result.

    Change .inner from inline-block to inline.

    .inner {
        display: inline;
    }
    

    html, body {
      width: 100%;
    }
    
    .outer {
      background-color: lavender;
      display: inline-block;
      max-width: 30%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .inner {
      display: inline;
    }
    
    .inner>* {
      display: inline;
    }
    
    .inner>:first-child::after {
      content: "~"
    }
    <html>
    
      <body>
        <div class="outer">
          <div class="inner">
            <div>left1</div>
            <div>right1</div>
          </div>
          <div class="inner">
            <div>left2</div>
            <div>right2</div>
          </div>
          <div class="inner">
            <div>left3</div>
            <div>right3</div>
          </div>
          <div class="inner">
            <div>left4</div>
            <div>right4</div>
          </div>
        </div>
      </body>
    
    </html>