Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS truncate element with children

Tags:

html

css

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>
like image 834
undefined Avatar asked May 13 '26 02:05

undefined


1 Answers

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>

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.

like image 139
Tomalak Avatar answered May 14 '26 14:05

Tomalak