Home > OS >  Fixed first table column with rowspan
Fixed first table column with rowspan

Time:06-14

I'm using a simple table template to be able to fix the first column. Working fine in many use cases but not in case the 'rowspan' is used.

HTML:

<table>
  <tbody>
    <tr>
      <td class='first'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td class='first' rowspan='3'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td class='first'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

CSS:

table td {
  border: 1px solid red;
  background: lightpink;
  min-width: 100px;
  max-width: 100px;
  width: 100px;
  height: 20px;
}

table td.first:nth-child(1) {
  border: 1px solid blue;
  background: lightblue;
  position: relative;
  display: block;
  width: 300px;
  min-width: 300px;
  max-width: 300px;
}

table tbody {
  position: relative;
  display: block; 
  overflow: scroll; 
  width: 500px;
}

table {
  position: relative;
  overflow: hidden; 
  border: 1px solid black;
}

JS (jQuery):

$('tbody').scroll(function(e) { 
  $('td.first:nth-child(1)').css("left", $("tbody").scrollLeft());
});

I need to have the first column with a specific width. And all other columns with different width. Unfortunately it is not working if the 'rowspan' is used and the first TD of each row is set to 'display: block'.

See my example: https://jsfiddle.net/zqjc9h0p/2/

CodePudding user response:

You can replace display: block with display: table-cell :

$('tbody').scroll(function(e) { 
  $('td.first:nth-child(1)').css("left", $("tbody").scrollLeft());
});
table td {
  border: 1px solid red;
  background: lightpink;
  min-width: 100px;
  max-width: 100px;
  width: 100px;
  height: 20px;
}

table td.first:nth-child(1) {
  border: 1px solid blue;
  background: lightblue;
  position: relative;
  display: table-cell;
  width: 300px;
  min-width: 300px;
  max-width: 300px;
}

table tbody {
  position: relative;
  display: block; 
  overflow: scroll; 
  width: 500px;
}

table {
  position: relative;
  overflow: hidden; 
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td class='first'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td class='first' rowspan='3'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td class='first'>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

  • Related