MasterOdin MasterOdin - 2 months ago 14
CSS Question

Style floating table headers

So I've been trying to accomplish getting floating table headers to work. Unfortunately I cannot use something like floatThead jQuery library as I need to hover different rows as you scroll through the table so I've come up with my own solution based on various other SO answers.

However, the problem is that the styling of the floating header does not match the styling of the non-floated header and I'm not sure why that is or the proper way to fix this.

Here's a jsFiddle illustrating my current code. The issue is that the first floating header which has different columns does not match the sizing of the non-floating header even though they both have percentage widths (that add up to 100%).

The important javascript:

var persist = $(".persist-area");
var z_index = 900;
var count = 0;
persist.each(function() {
var el = $(".persist-thead>tr", this);
el.before(el.clone()).css({"width": el.width(), "top": "0px", "z-index": "899"}).addClass('floating-thead');
$(".persist-header", this).each(function() {
var clone = $(this);
clone.before(clone.clone()).css({
"width": clone.width(),
"top": (0 + el.height()) + "px",
"z-index": "" + z_index
}).addClass("floating-header").removeClass("persist-header").attr('id', 'floating-header-' + count);
z_index++;
count++;
});
});


and css:

.floating-thead,
.floating-header {
position: fixed;
top: 0;
visibility: hidden;
}

.floating-thead > td,
.floating-header > td {
display: inline-block;
text-align: center;
}

Answer

Your trouble is the cells in the floating row are display: inline-block, which means the whitespace between elements has an effect on the rendered output.

Much more on ways around that in this answer (tldr: standard workaround options: remove the whitespace in your markup (easy), don't provide the closing tag (clearly bad practice, potentially risky), or make the font size for the parent element 0 and then specify the correct font size for the cells)

In your case though, you can just make them display: table-cell (just like the non-floating rows' cells).