HTML table with horizontal scrolling (four columns fixed)

8.2k views Asked by At

I've been struggling to create a table where the first four columns are fixed, whereas the rest of them have a horizontal scrolling. I found this example first column fixed

It has the first column fixed. I am very new to CSS and cannot extend to make the four first columns fixed. Any one could help? Sorry, that should be very simple, I just can't.

2

There are 2 answers

0
Caitbug On BEST ANSWER

CSS:

table {
  table-layout: fixed; 
  width: 100%;
  *margin-left: -100px;/*ie7*/
}
td, th {
  vertical-align: top;
  border-top: 1px solid #ccc;
  padding:10px;
  width:100px;
}
.col1{
  position:absolute;
  *position: relative; /*ie7*/
  left:0; 
  width:100px;
}
.col2{
  position:absolute;
  *position: relative; /*ie7*/
  left:100px; 
  width:100px;
}
.col3{
  position:absolute;
  *position: relative; /*ie7*/
  left:200px; 
  width:100px;
}
.col4{
  position:absolute;
  *position: relative; /*ie7*/
  left:300px; 
  width:100px;
}
.outer {position:relative}
.inner {
  overflow-x:scroll;
  overflow-y:visible;
  width:500px; 
  margin-left:400px;
}

Html:

<div class="outer">
  <div class="inner">
    <table>
        <tr>
          <th class="col1">Header A</th>
           <th class="col2">Header A</th>
             <th class="col3">Header A</th>
                <th class="col4">Header A</th>

          <td>col 2 - A (WITH LONGER CONTENT)</td>
          <td>col 3 - A</td>
          <td>col 4 - A</td>
          <td>col 5 - A</td>
           <td>col 6 - B</td>
          <td>col 7 - B</td>
        </tr>
        <tr>
           <th class="col1">Header B</th>
            <th class="col2">Header B</th>
              <th class="col3">Header B</th>
                <th class="col4">Header B</th>

          <td>col 2 - B</td>
          <td>col 3 - B</td>
          <td>col 4 - B</td>
          <td>col 5 - B</td>
            <td>col 6 - B</td>
          <td>col 7 - B</td>
        </tr>
        <tr>
           <th class="col1">Header C</th>
            <th class="col2">Header C</th>
               <th class="col3">Header C</th>
                <th class="col4">Header C</th>

          <td>col 2 - C</td>
          <td>col 3 - C</td>
          <td>col 4 - C</td>
          <td>col 5 - C</td>
           <td>col 6 - B</td>
          <td>col 7 - B</td>
        </tr>
    </table>
  </div>
</div>

https://jsfiddle.net/h75zn59o/

Position:absolute; is what causes that first header column to be fixed. With the original CSS, it's just applied to "th", but using classes (in this example, col1, col2, etc.) we can assign different fixed positions to different columns. Because the columns are 100px wide, each following column is positioned another 100px left So, the first one is 0px, then 100px for col2, etc) to avoid overlap with the previous column.

1
Abhishek Patel On

Assign some class to the td tags you want scrollable and add overflow-x:scroll