简体   繁体   中英

JavaScript table to shrink to fit its content

The following code produces cells with higher height that needed I want cells to fit its inner canvas in order to draw a diagonal on them

 var miglobal = []; var ref1 = document.createElement("table"); var refx = document.createElement("tbody"); ref1.appendChild(refx); var ref2, ref3; console.log(ref1); for (var y = 0; y < 25; y++) { ref3 = refx.insertRow(y); for (var x = 0; x < 25; x++) { ref2 = ref3.insertCell(x); var cnv = document.createElement("canvas"); cnv.setAttribute("id", ("mycnv" + (y * 25 + x)).toString()); cnv.setAttribute("height", "30px"); cnv.setAttribute("width", "30px"); var cntx = cnv.getContext("2d"); cntx.moveTo(0, 0); cntx.lineTo(30, 30); cntx.stroke(); miglobal.push(cntx); ref2.appendChild(cnv); }; }; document.body.appendChild(ref1); 
 table { border: 2px black solid; } tr:hover { background: red; } tr >td { border: 2px solid black; padding: 0; } td > canvas { height: 100%; width: 100%; padding: 0; } 

All is generated dynamically because 25*25 at hand table could be cumbersome

By default, the canvas element is displayed as an inline element. This causes the generation of a line box with the canvas element by default aligned to the baseline of the line box. The extra space you are encountering is the space below the baseline (ie space for characters such as "g" that descend below the baseline).

In your example, you could change the canvas element to be displayed as a block element. For example...

td > canvas {
  padding: 0;
  display: block;
}

Or you could change the canvas element to be displayed with a different vertical alignment. For example...

td > canvas {
  padding: 0;
  vertical-align: middle;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM