Search code examples
htmlcsshtml-tablerowword-wrap

Make HTML table cell's content fit - without wrapping?


This is my situation :

  • I'm currently in the process of finalizing a rather... huge web application (PHP with CodeIgniter, MySQL, Javascript+Ajax+Jquery and using various Javascript libraries - e.g. dataTables)

The issue :

  • Let's say we've got a table, fixed-width.
  • The first column is also fixed-width. (Let's say at 200px)
  • When the table is populated :
    • If the contents of the first column occupy less than 200px space, it's ok.
    • If the contents exceed those 200px then the content is wrapped, thus creating a "double line" effect and higher rows than I'd wished.

Hint :

  • "Shrinking" a very very very long line to something like very very very ... is what I'm thinking. Is something like that even possible? Server-side?

How would you approach that? (preferably in an elegant way - 'coz, yep, I admit that I have a few solutions in mind, none of which seems... user-friendly... lol)


Solution

  • I think doing a string-truncation is impossible serverside, if you are not using a monospace font so that the same number of characters always has the same width. What you could do is a client-side string-truncation:

    (Nice code at Calculate text width with JavaScript):

    CSS:

    #testing-div
    {
        position: absolute;
        visibility: hidden;
        height: auto;
        width: auto;
    }
    

    JS:

    var test = document.getElementById("testing-div");
    test.style.fontSize = fontSize;
    var height = (test.clientHeight + 1) + "px";
    var width = (test.clientWidth + 1) + "px";
    

    You can loop through the entire length of the string, and keep adding a character to the body of #testing-div, calculating the width, and checking if it fits. Make sure you add the ... if the string is too long.