问题
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>
回答1:
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>
回答2:
You basically just need to remember that flex items can shrink by default (flex-shrink: 1
).
Once you disable flex-shrink
you should be all set.
div {
display: flex;
justify-content: space-between;
align-items: baseline; /* optional */
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* optional */
}
span:last-child {
flex-shrink: 0;
}
<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>
来源:https://stackoverflow.com/questions/49056401/when-using-nowrap-within-a-flex-row-avoid-pushing-the-last-elements-off-the-s