Text "leaks" behind th using CSS position sticky

5

I'm using position: sticky; in <thead> of a table where I assign a background color to <th> .

My intention is that when the page scrolls, the header remains visible because the table has many rows and this makes it much easier to read the data.

The problem is that the text that is rolled up appears behind the <th> of the table.

See an example:

/*
  Este código não tem nada a ver com o problema
  é só para o HTML não ficar quilométrico.
*/
let tr = document.getElementById('replicar')
let frag = document.createDocumentFragment()
let i = 30

while (i-- > 0) { frag.appendChild(tr.cloneNode(true)) }
tr.parentElement.appendChild(frag)
table {
  width: 100%;
  margin-top: 100px;
}

thead {
  position: sticky;
  top: 15px;
}

th {
  background-color: #babaca;
}
<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
      <th>Header 4</th>
    </tr>
  </thead>
  <tbody>
    <tr id="replicar">
      <td>Coluna 1</td>
      <td>Coluna 2</td>
      <td>Coluna 3</td>
      <td>Coluna 4</td>
    </tr>
  </tbody>
</table>

As Chrome does not support position: sticky in <thead> , follow one image:

I"solved" my problem by applying a box-shadow to my <thead> so that there is a "backdrop" that covers the text rolling back.

Here's an example with box-shadow red for easy viewing:

/*
  Este código não tem nada a ver com o problema
  é só para o HTML não ficar quilométrico.
*/
let tr = document.getElementById('replicar')
let frag = document.createDocumentFragment()
let i = 30

while (i-- > 0) { frag.appendChild(tr.cloneNode(true)) }
tr.parentElement.appendChild(frag)
table {
  width: 100%;
  margin-top: 100px;
}

thead {
  position: sticky;
  top: 15px;
  box-shadow: 0 -8px 0 8px red; /* Aqui seria branco */
}

th {
  background-color: #babaca;
}
<table>
  <thead>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
      <th>Header 4</th>
    </tr>
  </thead>
  <tbody>
    <tr id="replicar">
      <td>Coluna 1</td>
      <td>Coluna 2</td>
      <td>Coluna 3</td>
      <td>Coluna 4</td>
    </tr>
  </tbody>
</table>

Image:

My question is, is there a less playful way to do this?

Should I use another element to be able to have a background-color that overlaps the text?

    
asked by anonymous 05.12.2018 / 21:54

1 answer

-3

Maybe it would be better to use:

position: fixed;
top: 0;
    
10.12.2018 / 15:25