So there are some subtle issues with fixed positioning that make this particularly difficult.
Fixed elements are relative to the browser viewpoint
When you declare position: fixed
, any additional position rules (like left
or top
) will place the header relative to the viewport itself - the top left corner of the screen. You can't use any tricks to make it relative to its parent, either, since it will be in the same place whenever the page scrolls. This might not affect your web page, but it's still something to consider.
Fixed elements don't work as expected in mobile browsers
I don't know your specific use case, but it's food for thought.
Fixed positioning removes elements from normal flow
This is what's causing the problem, as far as I can tell. When position: fixed
is declared, the element actually breaks out of the normal layout and position of elements of the page, and now works in its own unique block.
From the CSS2 spec (this applies to fixed positioning as well):
In the absolute positioning model, a box is explicitly offset with respect to its containing block. It is removed from the normal flow entirely (it has no impact on later siblings). An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants. However, the contents of an absolutely positioned element do not flow around any other boxes. They may obscure the contents of another box (or be obscured themselves), depending on the stack levels of the overlapping boxes.
This is good, since you want the header to float above the table, but also bad because in most browsers, it's laid out separately from the rest of the table.
Potential fixes
If the only thing on the page is your table, you should be able to set the header to use width: 100%
and apply the same cell widths as the rest of the table. It might be hard to get the sizing to match up just right, though, especially when the window is resized.
Use some simple JavaScript to display the header. I know you want to keep this with HTML and CSS (I usually do too), but JavaScript fits well because the floating header shouldn't be an essential part of using the site. It should be available for browsers that support it, but those that don't should still be able to use the table. There's a very good technique at CSS-Tricks
(http://css-tricks.com/persistent-headers/), but you'll be able to find others by looking for "sticky table headers" on your favorite search engine.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…