parag patel
parag patel

Reputation: 3283

make first column sticky in react table with only CSS

I am trying to render first column of react table as sticky. It almost worked though first cell of each row is not really sticky as expected. here is codesandBox working sample code with issue. https://codesandbox.io/embed/objective-frog-m4imr?fontsize=14&hidenavigation=1&theme=dark. In this code, when I scroll over horizontally, first header in first column is sticky but rest of the header in first column is not sticky even though they have same CSS styling.

This question might be duplicate but I am looking for solution that does not need jQuery as I only want to use CSS. And also I don't want to use any other position like absolute or relative as mentioned in other questions.

If someone can help me solve this, that'd be great!

Upvotes: 3

Views: 10154

Answers (2)

parag patel
parag patel

Reputation: 3283

After hours of juggling around, the issue was overflow property given on the parent element tbody of tr. Once I remove overflow property from tbody itself, it would work and column 1 is sticky.

Though, as soon as I remove overflow from tbody styles, first column is sticky but another issue raised is first header row is not sticky anymore since there is no overflow styles given. However I making first row sticker is easy part, with position sticky only.

Solution:

for anyone who is using react table and want to make first column and first header stickier without package and jQuery, only CSS

https://codesandbox.io/s/objective-frog-m4imr?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 6

Matan Sanbira
Matan Sanbira

Reputation: 1513

table is a bit tricky to work on with new layout styling so I wrote a working POC using grid:

section {
  width: 600px;
  height: 200px;
  position: relative;
  overflow: scroll;
  display: grid;
  grid-template-columns: repeat(6, 200px);
  grid-template-rows: repeat(6, 50px)
}

div,
header {
  background: white;
  border: solid;
}

.rh {
  position: sticky;
  left: 0;
}

header {
  position: sticky;
  top: 0;
}

header:first-child {
  left: 0;
  z-index: 100;
}
<section>
  <header>header</header>
  <header>header2</header>
  <header>header3</header>
  <header>header4</header>
  <header>header5</header>
  <header>header6</header>
  <div class="rh">r-header</div>
  <div>text2</div>
  <div>text3</div>
  <div>text4</div>
  <div>text5</div>
  <div>text6</div>
  <div class="rh">r-header</div>
  <div>text2</div>
  <div>text3</div>
  <div>text4</div>
  <div>text5</div>
  <div>text6</div>
  <div class="rh">r-header</div>
  <div>text2</div>
  <div>text3</div>
  <div>text4</div>
  <div>text5</div>
  <div>text6</div>
  <div class="rh">r-header</div>
  <div>text2</div>
  <div>text3</div>
  <div>text4</div>
  <div>text5</div>
  <div>text6</div>
  <div class="rh">r-header</div>
  <div>text2</div>
  <div>text3</div>
  <div>text4</div>
  <div>text5</div>
  <div>text6</div>
</section>

Upvotes: 2

Related Questions