I need to render a long text within a one line. and an image in the end of the line (tight end of the screen).
Given a very long text, I have to simply truncate it. The text should now go into a second line because it is too long.
please see my code. how can avoid pushing the nice emoji out of the screen?
Please take into account that the elements on the right side might be dynamic. so giving a fixed width is not good enough.
div {
display:flex;
justify-content: space-between;
}
span {
white-space:nowrap;
overflow:hidden;
}
<div>
<span>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
<span>🛑</span>
</div>
Since both <span>
elements are overflow:hidden
, the second <span>
gets truncated as well.
One solution is to set only the text element to truncate.
Below, I've demonstrated that this also works with multiple icons.
body {
margin: 0;
}
div {
display: flex;
justify-content: space-between;
}
.text {
white-space: nowrap;
overflow: hidden;
}
<div>
<span class="text">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
<span>🛑</span>
<span>🛑</span>
<span>🛑</span>
</div>
Another solution is to prevent the icon from shrinking by setting flex-shrink
to zero.
Below, I'm using the flex
shorthand to set flex-grow
, flex-shrink
and flex-basis
.
(Also works with icons of varying widths and with multiple icons.)
body {
margin: 0;
}
div {
display: flex;
justify-content: space-between;
}
span {
white-space: nowrap;
overflow: hidden;
}
.icon {
flex: 0 0 auto;
}
<div>
<span>hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </span>
<span class="icon">🛑</span>
<span class="icon">🛑🛑</span>
</div>