I'm currently working on a jQuery project where I need to create a table with columns of exact widths.
For example, let's say I want the first column to be exactly 100px wide, including padding (10px on each side). I've tried various combinations of width()
and innerWidth()
functions, but encountered some unexpected results in my attempts:
I created a td element and set its width using
td1.width(100);
. However, when I checked the values usingtd1.width()
andtd1.innerWidth()
, they returned 120px and 140px respectively. The actual column width shown in the Firefox console was 140px.On another attempt, I used
td1.innerWidth(100);
instead. This time, the functions returned 100px fortd1.width()
and 120px fortd1.innerWidth()
. Again, the column width reported by Firefox was 120px.
I am puzzled as to why td1.width(100);
behaves in this strange manner?
But the real question remains: is there any way to achieve a column with an actual width of 100px, properly including padding?
.js file
var bodyTable = $("<table>");
var body = $("<tbody>");
var tr1 = $("<tr>");
var tr2 = $("<tr>");
$("#testTable").append(bodyTable);
bodyTable.append(body);
body.append(tr1);
body.append(tr2);
var td1 = $("<td>foo</td>");
var td2 = $("<td>foo</td>");
var td3 = $("<td>foo</td>");
var td4 = $("<td>foo</td>");
var td5 = $("<td>foo</td>");
var td6 = $("<td>foo</td>");
tr1.append(td1);
tr1.append(td2);
tr1.append(td3);
tr2.append(td4);
tr2.append(td5);
tr2.append(td6);
td1.width(100);
console.log(td1.width(), td1.innerWidth()); //Result: 120 140
td1.innerWidth(100);
console.log(td1.width(), td1.innerWidth()); //Result: 100 120
.css file
#testTable td {
padding:10px;
}
.html file
<div id="testTable"></div>