Ruud Lenders Ruud Lenders - 1 month ago 7
CSS Question

When using border-collapse, how to compute border-bottom-width in JavaScript?

When using

table { border-collapse: collapse; }
combined with
th { border-bottom: 11px solid black }
, it seems impossible to compute the border-bottom-width in JavaScript.

window.getComputedStyle(th).getPropertyValue('border-bottom-width')
does not help at all. Just see what this fiddle logs to the console in different browsers...


  • Chrome:
    11px

  • IE11:
    5.5px

  • Firefox:
    6px



If I remove
border-collapse
all browsers return
11px
, as I would expect.

Is there a more reliable way to get the precise border-width when using
border-collapse
? OR is there a way to get the height (including borders) of either the
thead
,
tr
or
th
without running into the same inconsistencies between browsers?

Answer

Interesting! Seems like it's a plain inconsistency between browsers, don't think there's a simple solution to this. Anyways, here's a hacky solution/workaround:

var th = document.getElementById('th');
var table = document.getElementById('table');
var style = window.getComputedStyle(th);

table.style.borderCollapse = 'separate';
var borderHeight = style.getPropertyValue('border-bottom-width');
table.style.borderCollapse = 'collapse';
console.log(borderHeight);
table {
  border-collapse: collapse;
}
th {
  border-bottom: 11px solid red;
}
<table id="table">
  <tr>
    <th id="th">TH</th>
  </tr>
</table>

Tested in Chrome & Firefox, both returned 11px.


EDIT: Based on @Eric N's answer, you might get lucky adding display: block to the ths. That would break the table layout then and you would need to work around that. Example for that:

var th = document.getElementById('th');
var style = window.getComputedStyle(th);

var borderHeight = style.getPropertyValue('border-bottom-width');
console.log(borderHeight);
table {
  border-collapse: collapse;
}
th {
  display: block;
  float: left;
  border-bottom: 11px solid red;
}
<table id="table">
  <tr>
    <th id="th">TH</th>
    <th>TH</th>
    <th>TH</th>
  </tr>
</table>