How to change the font size in the table cells in accordance with the contents of the cells?

I have an HTML table that increments numbers, starting from 0 in its cells (from left to right, to the bottom).

I fixed the width and height cells in the CSS (width 40 pixels, height 25 pixels in my case).

When the table becomes larger, the numbers inside it become large (for example, the last number is 1266356). This causes the cells to be wider than I defined in CSS, which expands the table accordingly.

Instead, I would like the font of the numbers to be smaller in order to keep the cell width 40px.

How can I accomplish this with CSS / Javascript / jQuery?

+4
source share
4 answers

There is probably a smart CSS way to do this, but in jQuery something like the following might do the trick:

 // if the length exceeds a predefined limit if($('.someCell').text().length > 5) { // change the font size of it text $('.someCell').css("font-size", "8px"); } 
+4
source

You can scroll through the rows and cells in the table and check the length of innerHTML. It might look something like this:

 var tableRows = document.getElementById("myTable").rows; maxLength = 5; for(var i = 0; i<rows.length;i++) { var rowCells = tableRows[i].cells.length; for(var a = 0; a<rows.length;a++) { if(rowCells[a].innerHTML.length > maxLength) { rowCells[a].style.fontSize = "8px"; } } } 
+2
source

Here is what I do in my dropdownReplacement plugin :

using the detectCharWidth function, I calculate the width of the text avg char in the div, then I can multiply this by the length of the text to see if it matches the input.

at this point you can change the font for me less

here is the function:

 var detectedCharWidths = {}; var detectCharWidth = function(testText){ var val = testText || "abcdef 1 2 3 4 5 6 ABCDEF ! ! %"; //correct detection depends on this more then anything if(!detectedCharWidths[val]){ var $inp = $("<span>", { "text":val, // "class":opts.selectClass, "css": {"background":"none", "margin":0, "padding":0, "overflow":"visible", "width":"auto", "color":"#FFF"} }); $body.append($inp); detectedCharWidths[val] = ($inp.width() / val.length); $inp.remove(); } return detectedCharWidths[val]; } 

which should help you with this.

0
source

I wrote one function that will help you customize the font depending on the container.

 function adjustFont(x) { if (x.height() <= 36) return x.css("font-size"); else { var sizeInPx = x.css("font-size").split("px")[0]; x.css("font-size", (sizeInPx - 1) + "px"); adjustFont(x); } } 

Change the height to suit your needs. I fixed it o 36.

And you need to pass your td element:

 adjustFont($(yourTdElementHere)); 

If you want, you can scroll through the table and pass each item.

0
source

Source: https://habr.com/ru/post/1307678/


All Articles