Filth
Filth

Reputation: 3228

Fixed table header scroll both horizontal and vertical CSS ONLY

Firstly, is it possible to achieve this using only CSS?

I have built a table that can scroll both horizontally and vertically however, I want to have the header encapsulated within it's container and not appear outside of the wrapper. So that when you scroll horizontally the corresponding header is in line with the content of it's designated column.

Using different variations of position: absolute and position: static give me some intended results but not the complete solution.

You'll note the width applied to the section element to give the effect of scrolling horizontally within the enclosed region.

Here is a JSFIDDLE example of what I have so far and CSS below to reference

https://jsfiddle.net/ko6qco1r/

html, body{
  margin:0;
  padding:0;
  height:100%;
}
section {
  position: relative;
  border: 1px solid #000;
  padding-top: 37px;
  background: grey;
  width: 300px;
}

.container {
  overflow-y: auto;
  overflow-x: scroll;
  height: 200px;
}
table {
  border-spacing: 0;
  width:100%;
}
td + td {
  border-left:1px solid #eee;
}
td, th {
  border-bottom:1px solid #eee;
  background: white;
  color: #000;
  padding: 10px 25px;
}
th {
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  color: transparent;
  border: none;
  white-space: nowrap;
}
th div{
  position: absolute;
  background: transparent;
  color: #fff;
  padding: 9px 25px;
  top: 0;
  margin-left: -25px;
  line-height: normal;
  border-left: 1px solid black;
}
th:first-child div{
  border: none;
}

Upvotes: 4

Views: 10642

Answers (1)

serraosays
serraosays

Reputation: 7869

This is another one of those interesting challenges (like vertical centering) brought to us by the inaction of the W3C. Also like vertical centering, you can't put a fixed header on a table with a horizontal scrollbar using position: fixed; on the thead element. But you do have a couple of options.

Option 1 - Horizontal Scrolling (http://codepen.io/staypuftman/pen/JXbpvZ)

The key here is to reestablish your table layout as table-layout: fixed; CSS-tricks has a good piece on this approach and then put a min-width value on your container when you want the scrollbars to appear. This makes the table scrollable left to right and maintains the integrity of the column headers on smaller devices. But the header is not fixed.

Option 2 - Fixed Header (https://jsfiddle.net/dPixie/byB9d/3/light/)

Your code looked like a rip-off of this guy's work, so I thought I'd repost here to give him some credit. This approach creates a series of <div> elements that mirror the contents of the <th> elements and uses some VERY creative positioning techniques to get it all to work.

There is a much better run-down on Salzar design that shows some examples and explains in detail all the complicated maneuvers to get this right.

Upvotes: 3

Related Questions