Liron Harel
Liron Harel

Reputation: 11247

How to implement single-line ellipsis with CSS

I want to be able to add three dots and maintain a text in a single line in a responsive design.

So for example:

I have a link with a link inside a container element (e.g. <span>). If the text is long, it will shown in two lines one a small screen:

This is a very long text
and it wraps because it's very long

I want that text to be shown like this:

This is a very long text...

text-overflow: ellipsis; works if you have set a width to the container, but in responsive design and on my web app it's not specified obviously.

Here's the HTML:

<div class="itm-title">
  <a href="/friendly-url-sample/">This is a very long sentence and I don't want it to wrap, I want three dots</a>
</div>

Is there a solution in CSS or jQuery that can solve this? thanks.

Upvotes: 73

Views: 75289

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You actually don't need width to be "set" here. All the elements in the responsive design have their width. You can just do it around with the following rules:

white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

Comment: This doesn't work with anchor:

a {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<a href="#">Pages you view in incognito tabs won’t stick around in your browser’s history, cookie store, or search history after you’ve closed all of your incognito tabs. Any files you download or bookmarks you create will be kept. Learn more about incognito browsing.</a>

It works! :)

  • No width set.
  • Using <a> tag.

Updated with OP's Code

.itm-title {
  width: 150px;
}
a {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div class="itm-title">
  <a href="/friendly-url-sample/">This is a very long sentence and I don't want it to wrap, I want three dots</a>
</div>

Result: Works!

Upvotes: 113

Related Questions