0

I'm trying to make a table with first column fixed, and it worked. ( how do I create an HTML table with fixed/frozen left column and scrollable body? )

However, some of styles are not applied to the fixed column even if its parent node does.

For example,

.even {
  background-color: #c0c0c0;
}
.fixed-col {
  position: absolute;
  left: 0;
  width: 50px;
}
table {
  margin-left: 50px;
}
<div style="position:relative;">
  <div style="overflow-x:scroll">
    <table>
      <tr class="even">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
      <tr class="odd">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
      <tr class="even">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
    </table>
  </div>
</div>

it looks like this enter image description here.

I want to make the fixed columns' background color striped as other columns. How can I fixed this?

Community
  • 1
  • 1
Takayuki Sato
  • 1,023
  • 1
  • 14
  • 22
  • when in position fixed or absolute it is not seen by other element nor parent, you need to style the bg to the td itself, so add a selector such as : .even .fixed-col {} or simply .even td {} – G-Cyrillus May 24 '16 at 10:04

2 Answers2

2

You can update your selector to select the td themselves.

Absolute or fixed positionned element are not in the flow anymore and tr will only wrap the td that remains in the flow.

Added a border to the table, tr will not be drawn outside of it.

.even td {
  background-color: #c0c0c0;
}
.fixed-col {
  position: absolute;
  left: 0;
  width: 50px;
}
table {
  margin-left: 50px;
  /* let's see where table stands (so trs and tds in the flow */
  border:solid;
}
<div style="position:relative;">
  <div style="overflow-x:scroll">
    <table>
      <tr class="even">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
      <tr class="odd">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
      <tr class="even">
        <td class="fixed-col">a</td>
        <td>b</td>
        <td>c</td>
      </tr>
    </table>
  </div>
</div>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
1

As your even class just adds the background colour, why not use it on the fixed cells as well as the parent?

<tr class="even">
    <td class="fixed-col even">a</td>
    <td>b</td>
    <td>c</td>
</tr>
Starscream1984
  • 3,072
  • 1
  • 19
  • 27
  • 1
    As GCyrillus mentions in their comment - the absolute element is outside the flow of it's parent so doesn't inherit styles applied only to the parent – Starscream1984 May 24 '16 at 10:14