Css overflow ellipsis. Trimming single or multi-line text by height with the addition of an ellipsis. Ellipsis at the end of the text

Defines the visibility parameters of text in a block if the entire text does not fit into the specified area. There are two options: the text is cut off; the text is cut off and an ellipsis is added to the end of the line. text-overflow works if the block's overflow property is set to auto , scroll or hidden .

brief information

Designations

DescriptionExample
<тип> Indicates the type of the value.<размер>
A && BThe values ​​must be output in the order specified.<размер> && <цвет>
A | BIndicates that you need to select only one value from the proposed ones (A or B).normal | small-caps
A || BEach value can be used independently or together with others in any order.width || count
Groups values.[ crop || cross ]
* Repeat zero or more times.[,<время>]*
+ Repeat one or more times.<число>+
? The specified type, word, or group is optional.inset?
(A, B)Repeat at least A, but no more than B times.<радиус>{1,4}
# Repeat one or more times separated by commas.<время>#
×

Values

clip The text is clipped to fit the area. ellipsis The text is truncated and an ellipsis is added to the end of the line.

Example

text-overflow

The magnetic field negligibly dampens the great circle of the celestial sphere, in which case the eccentricities and inclinations of the orbits increase.



The result of this example is shown in Fig. 1.

Rice. 1. Ellipsis at the end of the text

Object model

An object.style.textOverflow

Note

Opera before version 11 uses the -o-text-overflow property.

Specification

Each specification goes through several stages of approval.

  • Recommendation - The specification has been approved by the W3C and is recommended as a standard.
  • Candidate Recommendation ( Possible recommendation) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
  • Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
  • Working Draft - A more mature version of a draft that has been discussed and amended for community review.
  • Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
  • Draft ( Draft specification) - the first draft version of the standard.
×

Many people have probably encountered the problem when some text needs to be displayed on one line. Moreover, the text can be quite long, and the width of the block in which this text is located is usually limited to at least the same size of the browser window. For these cases, the text-overflow property was invented, which was included in the CSS3 recommendation, and was first implemented in IE6, a very long time ago. When using this property for a block, if its text is wider than the block itself, then the text is cut off and an ellipsis is placed at the end. Although everything is not so simple here, we will return to this a little later.
With Internet Explorer everything is clear, what about other browsers? And although the text-overflow property is currently excluded from the CSS3 specification, Safari supports it (at least in version 3), Opera too (since version 9 version, although the property is called -o-overflow-text). But Firefox doesn’t, it doesn’t support it, and even in version 3 it won’t. It’s sad, but true. But maybe something can be done?

Of course, it can be done. When I searched the Internet about this property, and how to do it in Firefox, I came across a simple solution. The essence of the solution:

That's all. Read the article for details.
The solution is not bad, but there are problems:

  1. The text may be cut off in the middle (relatively speaking) of the letter, and we will see its “stump”.
  2. The ellipsis is always displayed, even when the text is smaller than the width of the block (that is, it does not fall out of it and the ellipsis is not needed).

Step one

Let's first focus on the second problem, namely how to avoid displaying ellipsis when it is not needed. After racking my brains and experimenting “a little,” I found a solution. I'll try to explain.
The point is that we need a separate block with an ellipsis that will only appear when the text takes up too much space in width. Then I came up with the idea of ​​a falling floating block. Although it sounds scary, it just means a block that is always there and pressed to the right, but when the width of the text becomes large, the text pushes the block onto the next line.
Let's move on to practice, otherwise it's difficult to explain. Let's set the HTML structure:

very long text

Not very compact, but I couldn’t do anything smaller. So, we have a container block DIV.ellipsis, a block with our text and another block that will contain the ellipsis. Note that the “ellipsis block” is actually empty, because we don’t need the extra three dots when we copy the text. Also, don’t be alarmed by the lack of additional classes, since this structure is well addressed using CSS selectors. And here is the CSS itself:
.ellipsis ( overflow: hidden; white-space: nowrap; line-height: 1.2em; height: 1.2em; border: 1px solid red; ) .ellipsis > DIV:first-child ( float: left; ) .ellipsis > DIV + DIV ( float: right; margin-top: -1.2em; ).ellipsis >

That's all. We check and make sure that it works as intended in Firefox, Opera, Safari. In IE there is a very strange, but predictable result. In IE6 everything is gone, but in IE7 it simply does not work, since it does not support generated content. But we'll come back to IE later.

For now, let's look at what we've done. First, we set the line-height and height of the main block, since we need to know the height of the block and the height of the text line. We set the same value for the margin-top of the block with an ellipsis, but with a negative value. Thus, when the block is not “reset” to the next line, it will be above the text line (one line), when it is reset, it will be at its level (in fact, it is lower, we just pull it one line up). To hide unnecessary things, especially when there is no need to show the ellipsis, we make overflow: hidden for the main block, so when the ellipsis is above the line, it will not be shown. This also allows us to remove text that falls outside the block (to the right edge). To prevent the text from unexpectedly wrapping and pushing the block with the ellipsis lower and lower, we make white-space: nowrap, thereby prohibiting hyphens - our text will always be on one line. For the block with text, we set float: left so that it does not immediately collapse the block with the ellipsis and takes up the minimum width. Since inside the main block (DIV.ellipsis) both blocks are floating (float: left/right), the main block will collapse when the text block is empty, so for the main block we set a fixed height (height: 1.2em). And lastly, we use the ::after pseudo-element to display the ellipsis. For this pseudo-element we also set a background to cover the text that will appear under it. We set a frame for the main block just to see the dimensions of the block; later we will remove it.
If Firefox supported pseudo-elements as well as Opera and Safari in terms of their positioning (setting position/float etc for them), then it would be possible not to use a separate block for ellipses. Try replacing the last 3 rules with the following:

.ellipsis > DIV:first-child::after ( float: right; content: "..."; margin-top: -1.2em; background-color: white; position: relative; )

in Opera and Safari, everything works as before, and without the additional ellipsis block. But Firefox is disappointing. But it is for him that we make the decision. Well, you'll have to make do with the original HTML structure.

Step two

As you may have noticed, we got rid of the problem of ellipses appearing when the text fits in a block. However, we still have one more problem - the text is cut off in the middle of the letters. And besides, it doesn't work in IE. To overcome both, you need to use the native text-overflow rule for browsers, and only for Firefox use the solution described above (there is no alternative). We’ll figure out how to make a solution “only for Firefox” later, but now let’s try to make what we have work using text-overflow. Let's tweak the CSS:

.ellipsis ( overflow: hidden; white-space: nowrap; line-height: 1.2em; height: 1.2em; border: 1px solid red; text-overflow: ellipsis; -o-text-overflow: ellipsis; width: 100%; } .ellipsis * ( display: inline; ) /*.ellipsis > DIV:first-child ( float: left; ) .ellipsis > DIV + DIV ( float: right; margin-top: -1.2em; ) .ellipsis > DIV + DIV::after ( background-color: white; content: "..."; ) */

As it turned out, there is not much to edit. Three lines have been added to the main block style. Two of them include text-overflow. Setting the width to 100% is necessary for IE so that the text does not expand the block to infinity, and the text-overflow property works; essentially we limited the width. In theory, DIV, like all block elements, stretches across the entire width of the container, and width: 100% is useless, and even harmful, but IE has a problem with layout, since the container always stretches to fit the content, so there is no other way. We also made all internal elements inline, because for some browsers (Safari & Opera) text-overflow will not work otherwise, since there are block elements inside. We commented out the last three rules, since in this case they are not needed and break everything (conflict). These rules will only be needed for Firefox.
Let's see what we got and continue.

Step three

When I once again looked at the page (before I was going to write this article) mentioned at the very beginning, then, out of curiosity, I looked through the comments for smart related ideas. And I found it in a comment that talked about another solution that works in Firefox and IE (for this person, as for the author of the first article, apparently there are no other browsers). So, in this solution, the author deals with this phenomenon (the absence of text-overflow) in a slightly different way, attaching handlers to the overflow and underflow events to elements for which it was necessary to put an ellipsis if necessary. Not bad, but it seems to me that this solution is very expensive (in terms of resources), especially since it is somewhat glitchy. However, while figuring out how he achieved this, he came across an interesting thing, namely the CSS property -moz-binding. As far as I understand, this is an analogue of behavior in IE, only with a different sauce and cooler. But we won’t go into details, let’s just say that in this way you can attach a JavaScript handler to an element using CSS. It sounds strange, but it works. What are we doing:

.ellipsis ( overflow: hidden; white-space: nowrap; line-height: 1.2em; height: 1.2em; border: 1px solid red; text-overflow: ellipsis; -o-text-overflow: ellipsis; width: 100% ; -moz-binding: url(moz_fix.xml#ellipsis); zoom: 1;) .ellipsis * ( display: inline; ) .moz-ellipsis > DIV:first-child( float: left; display: block; } .moz-ellipsis > DIV + DIV( float: right; margin-top: -1.2em; display: block; } .moz-ellipsis > DIV + DIV::after( background-color: white; content: "..."; )

As you can see, we again made not many changes. At this step in IE7 there is a strange glitch, everything is skewed if you do not set zoom: 1 for the main block (the simplest option). If you remove (delete, comment out) the rule .ellipsis * or .moz-ellipsis > DIV + DIV (which does not affect IE7 at all), then the glitch disappears. This is all strange, if anyone knows what's wrong, let me know. For now, we'll make do with zoom: 1 and move on to Firefox.
The -moz-binding property includes the moz_fix.xml file with an instruction with the identifier ellipsis. The contents of this xml file are as follows:

All this constructor does is add the moz-ellipsis class to the element for which the selector worked. This will only work in Firefox (gecko browsers?), so only in it the moz-ellipsis class will be added to the elements, and we can add additional rules for this class. That's what they wanted. I’m not entirely sure about the need for this.style.mozBinding = “”, but from experience with expression, it’s better to be on the safe side (in general, I’m not very familiar with this side of Firefox, so I could be mistaken).
You may be alarmed that this technique uses an external file and JavaScript in general. There is no need to be afraid. Firstly, if the file does not load and/or JavaScript is disabled and does not work, it’s okay, the user simply will not see the ellipsis at the end, the text will be cut off at the end of the block. That is, in this case we get an “unobtrusive” solution. You can see for yourself.

Thus, we got a style for the “Big Four” browsers, which implements text-overflow for Opera, Safari & IE, and emulates it for Firefox, not very well, but it’s better than nothing.

Step four

We could put an end to this point, but we would like to improve our solution a little. Since we can attach a constructor to any block and, accordingly, gain control over it, why not take advantage of this. Let's simplify our structure:

very long text

Oh yeah! I think you will agree with me - this is what you need!
Now let’s remove all unnecessary things from the style:
.ellipsis ( overflow: hidden; white-space: nowrap; line-height: 1.2em; height: 1.2em; text-overflow: ellipsis; -o-text-overflow: ellipsis; width: 100%; -moz-binding: url(moz_fix.xml#ellipsis); ) .moz-ellipsis > DIV:first-child ( float: left; ) .moz-ellipsis > DIV + DIV ( float: right; margin-top: -1.2em; ) .moz -ellipsis > DIV + DIV::after ( background-color: white; content: "..."; )

We've finally removed the red border :)
Now, let’s add a little to our moz_fix.xml:

What's going on here? We are recreating our initial HTML structure. That is, those difficulties with blocks are done automatically, and only in Firefox. JavaScript code is written in the best traditions :)
Unfortunately, we cannot avoid the situation when the text is cut off in the middle of the letter (though, perhaps temporarily, since my solution is still very crude, and it may work in the future). But we can smooth out this effect a little. To do this we need an image (a white background with a transparent gradient), and a few changes to the style:
.moz-ellipsis > DIV:first-child ( float: left; margin-right: -26px;) .moz-ellipsis > DIV + DIV ( float: right; margin-top: -1.2em; background: url(ellipsis.png) repeat-y; padding-left: 26px; }

Let's look and enjoy life.

Let's put an end to this.

Conclusion

I’ll give you a small example for third-party layout. I took the table of contents of one of the Wikipedia pages (the first one that came up) and applied the method described above to it.
In general, this solution can be called universal only with a stretch. It all depends on your layout and its complexity. You may need a file, or maybe a tambourine. Although in most cases, I think it will work. And then, you now have a starting point ;)
I hope you learned something interesting and useful from the article;) Learn, experiment, share.
Good luck!

How sometimes annoying are the long names of product links - three lines each - or the long headings of other blocks. How great it would be if this whole thing could be somehow narrowed down, made more compact. And when you hover the mouse over it, show the title in full.

For this, our favorite CSS will come to our aid. It's very simple, look.

Let's say we have a block like this from a product catalog:

Here is its structure:

Miracle Yudo evening power giver, mysterious, art. 20255-59

A wonderful product at a super price, only 100 rubles. It will brighten up your lonely evenings and give you a surge of vitality!

Here are his styles:

Someblock( border: 1px solid #cccccc; margin: 15px auto; padding: 10px; width: 250px; ) .header( border-bottom: 1px dashed; font-size: 16px; font-weight: bold; margin-bottom: 12px ; )

Agree, it looks terrible. Of course, you can shorten the name of the product. But what if there are hundreds or thousands of them? You can also use PHP to trim off part of the name, limiting it to a certain number of characters. But what if the layout changes later and the blocks are smaller or, on the contrary, 2-3 times larger? None of this is an option, none of this suits us.

And here CSS and its magical property come to our aid text-overflow. But it needs to be used correctly in conjunction with several other properties. Below I will show you a ready-made solution, after which I will explain what’s what.

So, putting aside manual editing of product names and programmatic cropping of styles, we take CSS into our hands and see what we get:

Miracle Yudo evening power giver, mysterious, art. 20255-59

A wonderful product at a super price, only 100 rubles. It will brighten up your lonely evenings and give you a surge of vitality!

Well, is it better? In my opinion, very much so! And move your mouse over the title... voila! Here it is shown to us in full.

Nothing has changed in our structure, I just added a diva with a class .header title tag. And here are the new, updated styles:

Someblock( border: 1px solid #cccccc; margin: 15px auto; padding: 10px; width: 250px; ) .header( border-bottom: 1px dashed; font-size: 16px; font-weight: bold; margin-bottom: 12px ; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; )

Look what we did:

  • We added a property to the block white-space: nowrap, which removes the ability of the text to wrap words onto a new line, thereby stretching it into a line;
  • Then we added the property overflow: hidden, which limited the visibility of our line to the width of the block, thereby cutting off all unnecessary and not showing it to the visitor;
  • Well, at the end we added an ellipsis to our line using the property text-overflow: ellipsis, thereby letting the visitor understand that this is not the end of the line, and that they probably need to lift their mouse and look at it in full.

Love CSS, learn CSS, and website building won't seem so difficult to you =)


Vlad Merzhevich

Despite the fact that large diagonal monitors are becoming more affordable and their resolution is constantly increasing, sometimes the task arises of fitting a lot of text in a limited space. For example, this may be needed for a mobile version of the site or for an interface in which the number of lines is important. In such cases, it makes sense to trim long lines of text, leaving only the beginning of the sentence. This way we will bring the interface to a compact form and reduce the amount of information displayed. The line trimming itself can be done on the server side using the same PHP, but it’s easier through CSS, and you can always show the entire text, for example, when you hover the mouse cursor over it. Next, we’ll look at methods for cutting text with imaginary scissors.

In reality, it all comes down to using the overflow property with the value hidden . The differences only lie in the different display of our text.

Using overflow

In order for the overflow property to show itself with text in all its glory, you need to unwrap the text using white-space with the value nowrap . If this is not done, then the effect we need will not occur; hyphens will be added to the text and the entire text will be displayed. Example 1 shows how to trim long text with a specified set of style properties.

Example 1. overflow for text

HTML5 CSS3 IE Cr Op Sa Fx

Text



The result of this example is shown in Fig. 1.

Rice. 1. The appearance of the text after applying the overflow property

As can be seen from the figure, there is generally one drawback - it is not obvious that the text has a continuation, so the user must be made aware of this. This is usually done using a gradient or ellipsis.

Adding a Gradient to Text

To make it clearer that the text on the right does not end, you can overlay a gradient from a transparent color to the background color on top of it (Fig. 2). This will create the effect of the text gradually dissolving.

Rice. 2. Gradient text

Example 2 shows how to create this effect. The style of the element itself will remain practically the same, but we will add the gradient itself using the ::after pseudo-element and CSS3. To do this, we insert an empty pseudo-element through the content property and apply a gradient to it with different prefixes for major browsers (example 2). The width of the gradient can be easily changed using width , you can also adjust the degree of transparency by replacing the value 0.2 with your own.

Example 2: Gradient over text

HTML5 CSS3 IE 8 IE 9+ Cr Op Sa Fx

Text

An intra-discrete arpeggio transforms a polyseries; this is a one-time vertical in a super polyphonic fabric.



This method does not work in Internet Explorer up to version 8.0 inclusive, because it does not support gradients. But you can abandon CSS3 and make a gradient the old fashioned way, through an image in PNG-24 format.

This method can only be combined with a plain background, and in the case of a background image, the gradient on top of the text will be noticeable.

Ellipsis at the end of the text

You can also use an ellipsis at the end of cropped text instead of a gradient. Moreover, it will be added automatically using the text-overflow property. It is understood by all browsers, including older versions of IE, and the only drawback of this property is that its status is currently unclear. CSS3 seems to include this property, but the code with it does not pass validation.

Example 3 shows the use of the text-overflow property with the value ellipsis, which adds an ellipsis. When you hover your mouse over the text, it is displayed in its entirety and highlighted in a background color.

Example 3: Using text-overflow

HTML5 CSS3 IE Cr Op Sa Fx

Text

The unconscious causes a contrast, this is designated by Lee Ross as the fundamental attribution error, which can be seen in many experiments.


The result of this example is shown in Fig. 3.

Rice. 3. Text with ellipses

The big advantage of these methods is that the gradient and ellipses are not displayed if the text is short and fits entirely into a given area. So the text will be displayed as usual when it is completely visible on the screen and will be cut off when the width of the element is reduced.

There is text of arbitrary length that needs to be displayed inside a block of fixed height and width. In this case, if the text does not fit completely, a fragment of text that completely fits into the given block should be displayed, after which an ellipsis is set.

This task is quite common, but at the same time it is not as trivial as it seems.

Option for single line text in CSS

In this case, you can use the text-overflow: ellipsis property. In this case, the container must have the property overflow equal hidden or clip

Block ( width : 250px ; white-space : nowrap ; overflow : hidden ; text-overflow : ellipsis ; )

Option for multiline text in CSS

The first way to trim multiline text using CSS properties is to apply pseudo-elements :before And :after. Let's get started with HTML markup

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

And now the properties themselves

Box ( overflow : hidden ; height : 200px ; width : 300px ; line-height : 25px ; ) .box :before ( content : "" ; float : left ; width : 5px ; height : 200px ; ) .box > * :first -child ( float : right ; width : 100% ; margin-left : -5px ; ) .box :after ( content : "\02026" ; box-sizing : content-box ; float : right ; position : relative ; top : -25px ; left : 100% ; width : 3em ; margin-left : -3em ; padding-right : 5px ; text-align : right ; background-size : 100% 100% ; background : linear-gradient (to right , rgba (255 , 255 , 255 , 0 ), white 50% , white ); )

Another way is to use the column-width property, with which we set the column width for multiline text. However, when using this method, it will not be possible to set an ellipsis at the end. HTML:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.

Block ( overflow : hidden ; height : 200px ; width : 300px ; ) .block__inner ( -webkit-column-width : 150px ; -moz-column-width : 150px ; column-width : 150px ; height : 100% ; )

There is a third way to solve multiline text using CSS for browsers Webkit. In it we will have to use several specific properties with the prefix -webkit. The main one is -webkit-line-clamp which allows you to specify the number of lines to be output in a block. The solution is beautiful but rather limited due to its work in a limited group of browsers

Block ( overflow : hidden ; text-overflow : ellipsis ; display : -webkit-box ; -webkit-line-clamp : 2 ; -webkit-box-orient : vertical ; )

Option for multiline text in JavaScript

Here an additional invisible block is used, in which our text is initially placed, after which it is removed one character at a time until the height of this block becomes less than or equal to the height of the desired block. And at the end the text is moved to the original block.

var block = document. querySelector(".block"), text = block. innerHTML, clone = document. createElement("div"); clone style. position = "absolute" ; clone style. visibility = "hidden" ; clone style. width = block . clientWidth + "px" ; clone innerHTML = text ; document. body. appendChild(clone); var l = text . length - 1 ; for (; l >= 0 && clone . clientHeight > block . clientHeight ; -- l ) ( clone . innerHTML = text . substring ( 0 , l ) + "..." ; ) block . innerHTML = clone . innerHTML ;

This is the same as a plugin for jQuery:

(function ($ ) ( var truncate = function (el ) ( var text = el . text (), height = el . height (), clone = el . clone (); clone . css (( position : "absolute" , visibility : "hidden" , height : "auto" )); el . after (clone ); var l = text . length - 1 ; for (; l >= 0 && clone . height () > height ; -- l ) ( clone . text ( text . substring ( 0 , l ) + "..." ); ) el . text ( clone . text ()); clone . remove (); ); $ . fn . truncateText = function () ( return this . each (function () ( truncate ($ (this )); )); ); )(jQuery ));



Have questions?

Report a typo

Text that will be sent to our editors: