Trimming single or multi-line text by height with the addition of an ellipsis. Three dots at the end of a line using CSS Css three dots at the end

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 using php cut 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 text-overflow property comes to our aid. 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 software cropping of styles, we take CSS 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 div with the .header class and the 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 the white-space: nowrap property to the block, which removes the ability for the text to wrap words onto a new line, thereby stretching it into a line;
  • Then we added the overflow: hidden property, which limited the visibility of our line to the width of the block, thereby cutting off all the excess and not showing it to the visitor;
  • Well, at the end we added an ellipsis to our line using the text-overflow: ellipsis property, thereby letting the visitor know that this is not the end of the line, and that they probably need to move their mouse and look at it in full.

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


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 was looking on the Internet about this property, and how to do it in Firefox, I came across simple solution. The essence of the solution:

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

  • The text may be cut off in the middle (relatively speaking) of the letter, and we will see its “stump”.
  • 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 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 afraid of the lack of additional classes, since this structure well addressed through 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 ellipsis. 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 CSS properties o -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 with 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. Contents of this xml file following:

    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 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 decision 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!

    The introduction of CSS3 entails revolutionary changes in the daily routine of web designers. CSS3 continues to amaze us every day. Things that previously could only be done with using javascript, are now easily done with CSS3. For example, the Text-Overflow property.

    Sometimes in the process of creating websites we need to hide part of the dynamic text without moving to the next line. That is, insert long text into a table with a fixed width. At the same time, it is necessary to show the user that the visible part of the text is not everything. There is also a hidden part. This can be shown using an ellipsis (...).

    With CSS3 we can easily do this using the CSS text-overflow property

    Marking

    Text-overflow: ellipsis;

    Meaning ellipsis allows you to add an ellipsis after the text (...)

    The text-overflow: ellipsis property is useful when:

    1. Text extends beyond the cell
    2. There is free space in the cell: nowrap.

    We have a div with a width of 150 pixels to display the names of companies from the database. But at the same time, we don’t want long company names to jump to a new line and spoil appearance tables. That is, we need to hide text that extends beyond 150 pixels. We also want to inform the user about this. So that he means that not the entire title is displayed. And we want all the text to be displayed when the mouse is hovered.

    Let's take a look at how we can do this using CSS3.

    Company-wrap ul li (
    text-overflow: ellipsis;
    overflow: hidden;
    white-space:nowrap; )



    • Company Name

    • Asset Management">Envestnet Asset Management

    • Russell Investments

    • Northwestern Mutual Financial Network

    • ING Financial Networks


    Browser support

    With cross-browser support of this property There is one small nuance. All except firefox display correctly perfectly. But, fortunately, there is a solution to this problem!

    Three dots in Firefox

    Unfortunately, gecko (the rendering engine in Firefox) does not support this property. However this browser supports XBL, with the help of which we will get out of this situation.

    Gecko is a free web page layout engine. Mozilla browsers Firefox, Netscape and others. Old names are "Raptor" and "NGLayout". Gecko's core concept is to support open web standards such as HTML, CSS, W3C DOM, XML 1.0 and JavaScript. Another concept is cross-platform. Today Gecko works on operating systems Linux, Mac OS X, FreeBSD and Microsoft Windows, as well as on Solaris, HP-UX, AIX, Irix, OS/2, OpenVMS, BeOS, Amiga and others.

    To display ellipsis in firefox, we need to add one line to the style sheet.

    if you want to disable the property, just add:


    Moz-binding: url("bindings.xml#none");

    The next step is to create a bindings.xml file in the same location where the stylesheet is stored. We can use any text editor for this! Copy the code below and name the file bindings.xml.





    document.getAnonymousNodes(this)[ 0 ]
    this.label.style
    this.style.display
    if(this.style.display != val) this.style.display= val

    this.label.value
    if(this.label.value != val) this.label.value= val



    var strings= this.textContent.split(/\s+/g)
    if(!strings[ 0 ]) strings.shift()
    if(!strings[ strings.length - 1 ]) strings.pop()
    this.value= strings.join(" ")
    this.display= strings.length ? "" : "none"


    this.update()


    this.update()

    Final code for all browsers

    Company-wrap ul li (
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url("bindings.xml#ellipsis");
    white-space: nowrap;
    overflow: hidden;
    }

    CSS3 is becoming the go-to tool for web designers around the world to create never-before-seen websites with minimal code. There are simple, literally one-line solutions that were previously only possible using Photoshop or javascript. Start learning the power of CSS3 and HTML5 today and you won't regret it!

    In order to stand out from the gray mass of translators and win your sympathy, dear readers, at the end of my lessons there will be wise thoughts and aphorisms. Everyone will find something of their own in these lines :)

    Bear with dignity what you cannot change.

    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 informationNotations Description Example
    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 p.clip ( white-space: nowrap; /* Disable line wrapping */ overflow: hidden; /* Crop everything that does not fit into the area */ background: #fc0; /* Background color */ padding: 5px ; /* Margins around the text */ text-overflow: ellipsis; /* Add an ellipsis */ )

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

    Result this example 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 - 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 - 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 amendments have been made by the project editors.
    • Draft (Draft specification) - the first draft version of the standard.
    ×

    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% ; )

    The third way to solve multiline text using CSS is for Webkit browsers. 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 ));

    Internet