how to truncate text with respect to div height?

10,243

Solution 1

Try the following CSS:

text-overflow: ellipsis;
overflow: hidden;
whitespace: no-wrap;

This only works for single lines. For multiple lines you need JavaScript.

Solution 2

Use overflow: hidden... I can get more specific if you post more code. – j-man86 just now edit

Solution 3

As mentioned earlier, the easiest way to solve the problem would be to add overflow:hidden to your div's CSS Style.

However, this will not help you add the ellipsis (dots) at the end of the wrapping and there is no way that I am aware of to do multi-line text wrapping (ending with the 3 dots at the end) using solely CSS.

The easier way would be to use jQuery (or similar JavaScript Libraries) to wrap the text and add the 3 dots at the end. Example:

Reference to another StackOverflow post about wrapping content using CSS and jQuery for single line and multi line text.

It's also sometimes recommended to process the content server-side and then display it processed on the page, but it's sometimes more convenient (or faster/easier) to just use JavaScript.

Here's a jQuery Plugin that will do the trick: jQuery DotDotDot

Solution 4

To hide the text, there is simple solution, add overflow:hidden css property in div like follow

<div style="overflow:hidden">your code</div>

However to show ... at the end, you need to get contents of div in javascript and use substr function there. This will be trial and error solution to figure out how many characters can be displayed in the div.

Solution 5

This question is tagged with javascript, so here's the missing answer.

You could iterate over each character or word (as in this example), while you check that the height is lower than your desired height. On each truthy step, you could overwrite the element content with its text, but without the last word/character.

In converte this case I converted the string in an array and pop it on each iteration. This removes the last part of our text, and makes sure that the loop doesn't go infiniteeeee...

/**
 * Truncates the text of an element depending its height.
 *
 * @param {Element} element
 * @param {Number} height
 */
function truncateByHeight(element, height) {
  var textContent = typeof element.textContent === 'undefined' ? 'innerText' : 'textContent';
  var parts = element[textContent].split(' ');

  while (parts.pop() && element.clientHeight > height) {
    element[textContent] = parts.join(' ');
  }
}


var element = document.querySelector('.box');

truncateByHeight(element, 120);
<div class="box">Cornua naturae fulgura uno coegit quisquis ad margine? Pluvialibus umentia vultus nulli nunc pendebat speciem emicuit! Margine tonitrua caecoque iapeto. Origine levius nam. Silvas valles temperiemque forma? Ignotas tegit. Hunc ligavit: summaque freta illas invasit deerat proximus. Caelo calidis securae mentes pronaque traxit.

Caligine omnia gentes. Posset aere certis eurus titan verba unus homini ora. Sed volucres. Campos effervescere flamina illi pondus umor. Cinxit obstabatque secrevit. Ligavit: natus aberant. Indigestaque regio rapidisque carmen coegit erat discordia liquidas. Ripis nix horrifer terrae dei tepescunt ad vos regio.

Nabataeaque fronde pluviaque vos terra tellure flexi. Neu habendum poena locoque ne. Dedit locoque nunc nebulas. Mentisque liquidum summaque porrexerat cepit. Litem mare. Surgere adhuc ipsa. Orbem hanc volucres iapeto habentem. Dissociata otia inminet nubibus passim erant iners. Semina praecipites reparabat spectent fuerat.</div>
Share:
10,243

Related videos on Youtube

Zain Shaikh
Author by

Zain Shaikh

Have experience of 10+ years using different programming languages including C#, PHP, JavaScript. Building highly sCalable and robust applications for enterprise projects and products. Have been working on NetSuite ERP Customization, Integration and SuiteCommerce for 6+ years. Proficient in NetSuite Customization using SuiteScript v1 and v2, SuiteFlow, SuiteBundler, etc. NetSuite Integrations (REST and SOAP), JavaScript, nodejs, RDBMS, NoSql, OO Design, Design Patterns, Algorithms, SOA and Web services.

Updated on September 14, 2022

Comments

  • Zain Shaikh
    Zain Shaikh over 1 year

    I have a div with height of 192px. I want to truncate text within div and want to show ... in the end. now due to large text, button is clipping as shown in the snapshot. This happens when I add html tags in it.

    enter image description here

    Can anyone help?

  • Vsevolod Krasnov
    Vsevolod Krasnov almost 7 years
    @ZainShaikh, fixed your fiddle: jsfiddle.net/dBxes/7 . In this answer the last style is incorrect, should be white-space: nowrap;
  • Zain Shaikh
    Zain Shaikh over 6 years
    @VsevolodKrasnov your fiddle does not wrap lines to 150px height.