Css table header position sticky

A table with both a sticky header and a sticky first column

High five to Cameron Clark who emailed me demoed this and showed me how cool it is. And indeed, Cameron, it is cool. When I shared that around, Estelle Weyl showed me a demo she made several years ago. That feels about right, Estelle is always a couple of years ahead of me.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

These are cool solutions 🙂 Here is my take on this: http://hgsweb.de/sticky/index.html Sources are located at: https://github.com/napengam/sticky

I had a similar need some time ago, when I needed to build a product comparison table, and I realized that having the first column always visible can be problematic on small screens, where there isn’t enough space. Instead, I preferred adding the label as custom attribute and fetch it with CSS attr(). I did use horizontal stickiness too, though, for the intermediate sections. Here’s the respective pen and a more detailed explanation.

All browsers will support th/thead sticky by the end of the year. “you can’t position tr or thead” is not true in Firefox/Safari, and is a crbug.com/702927 in Chrome. Chrome’s table rewrite is almost done, and with it, sticky bug will be fixed.

Have you tried this out using any assistive tech (VoiceOver, JAWS, etc)? Historically, they don’t have a great time whenever you get CSS to do anything “elaborate” on a table and get confused. It looks a great attempt otherwise however.

Wayne, this works in JAWS, VO, and NVDA because the wrapper has an accessible name & appropriate role, and the table has no display properties overriding its semantics. TalkBack on Android is not so good. I filed a bug in December because this technique can cause trouble: TalkBack does not recognize tables in parents with tabindex. I have screen reader support notes in my post Under-Engineered Responsive Tables, explaining the attributes. For positioning in Safari you may need to use -webkit-sticky and the may misbehave as well (be sure to test). I go into more detail and outline workarounds in Fixed Table Headers.

You could set also 2nd column sticky, just need to know its position from the left. In other words, you need to know the size of the 1st column. I used custom CSS properties for “fixed” columns sizes. Then used JS to make “fixed” columns resizable by user. Works like a charm! 🙂

Источник

Лип­кая шап­ка таб­ли­цы на CSS

Практически на всех сайтах есть таблицы. А если эти таблицы имеют более дюжины строк, то вам, рано или поздно, понадобится сделать шапку таблицы «липкой». Многие до сих пор делают это с помощью JavaScript, но есть способ на чистом CSS.

Position Sticky Скопировать ссылку

Как не выходить за рамки? Скопировать ссылку

К сожалению почти у всех таблиц, которые я встречаю, используется border-collapse: collapse . С этим свойством проще делать рамки для ячеек, но при этом сами рамки им уже не принадлежат, а как бы становятся частью самой таблицы. А это значит, что если шапка таблицы и стала липкой — рамки её ячеек всё равно прокручиваются вместе с таблицей.

Читайте также:  Python write to file example

Чтобы избавиться от этой проблемы, можно использовать border-collapse: separate . Да, с этим свойством рамки ячеек перестанут схлопываться, но нам это не помешает.

В некоторых дизайн-системах у ячеек есть только горизонтальные рамки, а значит достаточно просто указывать border-top или border-bottom . Но даже если вам нужно указать рамки со всех сторон, то есть много способов это сделать:

Рамки для конкретных сторон Скопировать ссылку

:root < --border-width: 2px; --border-color: #CED4DA; --border: var(--border-width) solid var(--border-color); >table < border-collapse: separate; border-spacing: 0; >thead < position: sticky; top: 0; >th, td < border-right: var(--border); border-bottom: var(--border); >th:first-child, td:first-child < border-left: var(--border); >thead tr:first-child th

Рамки как box-shadow Скопировать ссылку

В примере выше мы устанавливаем расстояние между ячейками с помощью border-spacing для таблицы и отступ для прилипания с помощью top для шапки, равный размеру рамки. А затем добавляем ячейкам тень box-shadow , имитирующую рамку.

Рамки как outline Скопировать ссылку

В примере выше мы повторяем трюк из предыдущего примера, но имитирурем рамку с помощью outline .

Источник

Position Sticky and Table Headers

The first is dangerous because you aren’t using semantic and accessible elements for the content to be read and navigated. The second is almost the same. You can go that route, but need to be really careful to re-apply semantic roles.

Anyway, none of that matters if you just stick (get it?!) to using a sticky value on those elements.

It’s probably a bit weird to have table headers as a row in the middle of a table, but it’s just illustrating the idea. I was imagining colored header bars separating players on different sports teams or something.

Anytime I think about data tables, I also think about how tricky it can be to make them responsive. Fortunately, there are a variety of ways, all depending on the best way to group and explore the data in them.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

A reminder, folks: don’t forget to add a scope attribute to your th elements.
Also, define a top (or bottom ) property for the sticky elements (can’t count the times I couldn’t understand why it didn’t work ‍♂️).

Here is my solution, it can also make first columns sticky. I copy parts of outerHTML of various table elements, and put this into the innerHTML of ‘sticky’ table elements. The source of the demo is on GIT https://github.com/napengam/sticky
and a demo to visualize the effect is here http://hgsweb.de/sticky/html/index.html Regards

I had to do this for work. I had a table with any number (from 5 to 30+) of columns. They wanted the header to be sticky and the first column to be sticky. The only way I could get it to work was to combine 4 tables and make it look like one. The “table header” was actually two tables in a div with overflow hidden. When there was a horizontal scroll I had to translate the non-sticky table of columns over in the opposite direction of the scroll to fake the horizontal scroll. The second sets of tables were located under the “table header” with a min-height of 60vh. This made it appear that the header was sticky but it was just scrolling what looked like the “table rows”. Again I had to match the translation for the one sticky column on scroll just in the y-axis. It was a pain to make, and after being approved for months and in beta the project owners all of the sudden didn’t like the table having its own vertical scroll and couldn’t even remember how badly they wanted that first sticky column. Sigh.

Читайте также:  O reilly javascript pdf

For the first option you could use other elements and use ARIA to apply the semantics and roles. Here’s an example – https://www.w3.org/TR/wai-aria-practices/examples/table/table.html. There are pros and cons of this technique so should be tested thoroughly but the option is there. This would be way easier to make responsive as well.

The browser vendors really need to get together on this and let us use sticky with

– to hell with the spec – and make sure borders behave themselves when they do so!

Good overview of how to achieve this look. I’m curious if there are any tricks for dealing with translucent objects that use sticky positioning. I’ve found in previous projects that all headers remain stickied underneath (or in some cases, on top of) the most ‘recent’ header to become sticky. I darkened the translucency and it offered acceptable contrast to thwart the bleed-through of text from below, but still looked janky and made the box-shadow around the header very intense. Perhaps something like sticky-displace with options over , under , and push ?

Is there a pseudo class for when the header is stuck? It would be nice if we could use css to add the box-shadow only when it is stuck.

Источник

A table with a fixed (sticky) header

Often, we come across situations where we have a table with lots of data in it. So when we scroll, the table header are hidden off screen, and soon we don’t know what columns we’re looking at. This problem can easily be addressed by wrapping the table in a div , and a bit of friendly CSS.

position: sticky

Sticky positioning is kind of a hybrid, between relative and fixed . To quote https://developer.mozilla.org/en-US/docs/Web/CSS/position, «The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left.» Basically, the element occurs in the normal document flow, until you scroll past a certain offset, at which point it sticks to the top of the specified container. We’re going to wrap our table in a div (which we’ll make scrollable by setting its height and overflow-y properties), and make the th s position in a sticky way. We’ll also collapse the internal borders of the table using the border-collapse property. Is it really that simple? It actually is. Here’s the code, in its full unadulterated glory (don’t worry, I didn’t include any spoiler from season 2 of The Umbrella Academy, but seriously, go watch it):

Читайте также:  Java httpurlconnection return code

HTML

    Sticky Header  charset="UTF-8" />  rel="stylesheet" href="src/styles.css" />   class="wrapper">    Number Name Superpower Email     1 Luther Super-strength luther@umbrella.edu   2 Diego Telekinesis diego@umbrella.edu   3 Allison Rumor allison@umbrella.edu   4 Klaus Seance klaus@umbrella.edu   5 Five Time-travel five@umbrella.edu   6 Ben Inter-dimensional monster ben@umbrella.edu   7 Vanya Apocalyptic destruction vanya@umbrella.edu   - Reginald [Spoiler] powers reginald@umbrella.edu   - Pogo Human communication pogo@umbrella.edu   - Cha-Cha Ruthlessness chacha@temps.comm   - Hazel Compassion hazel@temps.comm       

CSS

body  font-family: "Segoe UI", sans-serif; > table  width: 100%; border-collapse: collapse; > th, td  padding: 8px; > th  text-align: left; background: #eee; position: sticky; top: 0px; > .wrapper  border: 1px solid #ddd; width: 100%; height: 300px; overflow-y: auto; > 

Источник

Таблица с липкой шапкой

Инструкция как сделать липкую шапку таблицы без использования JavaScript и без jQuery. Фиксированные заголовки таблицы сделанные на чистом CSS.

Таблица с липкой шапкой

Если вы занялись задачей сделать липкий заголовок таблицы и смотрели уже какие для этого решения предлагает поиск гугла, то вы видели эти портянки js-кода с идеей дублирования заголовков таблицы.

На самом деле эта типовая задача решается при помощи всего лишь трёх строчек css-кода. И это в буквальном смысле.

Вот посмотрите такое DEMO таблицы:

ID 2 3 4 5
1 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
2 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
3 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
4 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
5 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
6 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
7 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
8 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
9 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
10 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
11 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
12 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
13 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
14 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
15 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
16 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
17 Второй столбик. Третьий столбик. Четвёртый столбик. Пятый столбик.
18 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
19 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.
20 Второй столбик. Третий столбик. Четвёртый столбик. Пятый столбик.

Ну как вам такое? Правда круто?

Эта таблица имеет самый обычный html:

 
Третий столбик. Четвёртый столбик. Пятый столбик.

Липкой шапку таблицы делает css-свойство position с установленным значением sticky . Плюс добавлены свойства top и z-index , чтобы всё работало правильно:

Так же у меня в этом блоке стилей прописаны фон шапки и цвет текста. Это для того чтобы стилизовать шапку таблицы:

 background-color: #3e5d75; color: #dedede; 

Поддержка браузерами свойства sticky для таблиц: https://caniuse.com

JavaScript

Как реализовать сортировку данных в HTML-таблице на сайте. Сделате таблицу сортируемой при клике по заголовку колонки просто добавив атрибут data-sort=»sort_table» в тег table, а так же добавьте готовый скрипт.

*** Авторизируйтесь чтобы писать комментарии.

Источник

Оцените статью