I have a container with the width: 500px.
In this container there are 2 strings, “iiiiiiiiiiiiiii” and “MMMMMMMMMMMMMMM”. You can clearly see that the “M” string is a lot wider than the “i” string, but both fit in the 500px screen.
If i make the container smaller, lets say 350px the M string is too wide and i want to remove some ‘M’s so it can fit as so:
In React i have the following data:
JavaScript
x
4
1
var i = 'iiiiiiiiiiiiiii';
2
var M = 'MMMMMMMMMMMMMMM';
3
var containerWidth = 500;
4
Based on what information do I shorten the strings?
I started out with if string.length > containerWidth / 10
, but thats not right because string-length != width. I can’t use getElementById
and then use .offsetWidth
Advertisement
Answer
You can do that with css only:
JavaScript
1
8
1
.container {
2
width: 350px;
3
border: 2px solid black;
4
padding: 20px;
5
white-space: nowrap;
6
overflow: hidden;
7
text-overflow: ellipsis;
8
}
JavaScript
1
4
1
<div class="container">
2
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
3
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
4
</div>
Will result in something like this. Run the snippet for a live demo.
JavaScript
1
5
1
---------------------
2
| IIIIIIIIIIIIIIIIII|
3
| MMMMMMMMMMMMMMM|
4
---------------------
5