Make the first table column sticky with CSS in HTML and CSS

Description

The following code shows how to make the first table column sticky with CSS.

Example


<!DOCTYPE html>
<html>
<head>
<style>
.myTable {<!-- w  w  w .  j  av  a  2s  .com-->
  border: none;
  border-right: solid 1px #DDEFEF;
  border-collapse: separate;
  border-spacing: 0;
  font: normal 13px Arial, sans-serif;
}

.myTable thead th {
  background-color: #EEE;
  border: none;
  color: #336B6B;
  padding: 10px;
  text-align: left;
  text-shadow: 1px 1px 1px #fff;
  white-space: nowrap;
}

.myTable tbody td {
  border-bottom: solid 1px #EEE;
  color: #333;
  padding: 10px;
  text-shadow: 1px 1px 1px #fff;
  white-space: nowrap;
}

.my-wrapper {
  position: relative;
}

.my-scroller {
  margin-left: 141px;
  overflow-x: scroll;
  overflow-y: visible;
  padding-bottom: 5px;
  width: 300px;
}

.myTable .my-sticky-col {
  border-left: solid 1px #EEE;
  border-right: solid 1px #EEE;
  left: 0;
  position: absolute;
  top: auto;
  width: 120px;
}
</style>
</head>
<body>

  <div class="my-wrapper">
    <div class="my-scroller">
      <table class="myTable">
        <thead>
          <tr>
            <th class="my-sticky-col">Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
            <th>Header 4</th>
            <th>Header 5</th>
            <th>Header 6</th>
            <th>Header 7</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td class="my-sticky-col">A</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
          </tr>
          <tr>
            <td class="my-sticky-col">B</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
          </tr>
          <tr>
            <td class="my-sticky-col">C</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
          </tr>
          <tr>
            <td class="my-sticky-col">D</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
          </tr>
          <tr>
            <td class="my-sticky-col">E</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</body>
</html>

Click to view the demo





















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table