Flatiron Blog: The CSS Trick I Forget Every Time
November 21, 2017
q: what’s a trick in css you have to google every time?
a: literally any time i have had to put an ellipsis in text, especially if it is in a responsive container and/or the text itself varies, i have to google how to add an ellipsis wherever the text gets cut off. every. time. let me start by just giving the answer, a.k.a. create one more page that gives me the answer for when i inevitably have looking it up again.
.truncate-with-ellipsis {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
okay, so let’s go through each line:
.truncate-with-ellipsis
add a class to the container of the text that is only used for truncation. (the text should be directly in whatever container you’re applying this class to.)
width: 250px;
there has to be a width set on the container so the container has a limit for when to show an ellipsis. otherwise it doesn’t know when to break so it just won’t.
white-space: nowrap;
explicitly tell it not to wrap the overflow text so that it won’t just skip to the next line when it hits the container’s width limit.
overflow: hidden;
hide the overflowing text because that’s our goal to begin with! if the overflow text isn’t hidden it won’t wrap to the next line so it will just overflow over the edge of the container and still be visible. (think every site that hasn’t gotten enough attention from developers re: responsiveness.)
text-overflow: ellipsis;
set the overflow text that is being hidden when it passes the container’s width limit to be replaced with an ellipsis.
and that’s it! super straight forward but i always forget one of the four lines and have to look it up again. i’ve had this page bookmarked for a long time and whenever i go to it it’s like visiting an old friend. 😊
after talking about it so much here’s an example of what i’m even referring to:
(inspect to see what content is actually in that container. happy coding!)