Home > Mobile >  CSS truncate element with children
CSS truncate element with children

Time:11-01

I have a flex container with childs span elements:

<div>
    <span class="truncate">
        lorem ipsum lorem ipsum lorem ipsum
    </span>
    
    <span class="truncate">
        bbbb
    </span>
</div>

I want to truncate the whole element and not an individual part of it ( e.g the span ).

Is there any way to achieve this and still use the above structure? I want one ellipsis at the end.

div {
    display: flex;
  background-color: hotpink;
    max-width: 200px;
}

span {
    margin-right: 10px;
}


.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

body {
    margin: 100px;
}
<div>
    <span class="truncate">
        lorem ipsum lorem ipsum lorem ipsum
    </span>
    
    <span class="truncate">
        bbbb
    </span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I want to truncate the whole element and not an individual part of it

If you want to truncate the <div>, the <div> should have the .truncate class.

div {
  max-width: 200px;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<div class="truncate">
  <span>lorem ipsum lorem ipsum lorem ipsum</span>
  <span>bbbb</span>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can't have both display: flex; and text-overflow: ellipsis; on the same element.

That practically rules out having the <div> as flex parent, and the <span>s as flex children, and still get a coherent text overflow effect. text-overflow is an inline (!) text rendering feature. It requires a contiguous range of text that overflows a single container. Flex is practically block layout. You can't have it both ways, unfortunately.

  • Related