Tuesday, September 28, 2021

Fix column in custom scrollable table using LWC in salesforce

This post explains how to fix the column in custom table using lightning web component.


Below is the demo of output:

Fix column in LWC salesforce



fixColumn.cmp :


<template>
    <div class="table-scroll">
        <table>
            <thead>
                <tr>
                    <th class="fix">
                        <div> Head </div>
                    </th>
                    <th>
                        <div> Head 1 </div>
                    </th>
                    <th>
                        <div> Head 2 </div>
                    </th>
                    <th>
                        <div> Head 3 </div>
                    </th>
                    <th>
                        <div> Head 4 </div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td class="fix">
                        <div> Lovesalesforceyes </div>
                    </td>
                    <td>
                        <div> Fix column </div>
                    </td>
                    <td>
                        <div> with </div>
                    </td>
                    <td>
                        <div> LWC </div>
                    </td>
                    <td>
                        <div> Salesforce </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

fixColumn.css :


table {
 background-color: white;
}
.table-scroll {
  overflow: auto;
}
table th{
  min-width: 140px;
  height: 50px;
  text-align: center;
}
table td{
  height: 50px;
  text-align: center;
}
.fix{
    position: sticky;
    left: 0;
    z-index: 1;
    background: #f8f8f8;
 }


Explanation :


Basically this is just a two line CSS work. Main thing you have to look at in this code is to fix class CSS. Position fix the first column and z-index show the first column above over other columns. Left is 0 because the requirement is to fix the first column. If you have to fix more than the first column then you have to adjust left according to that. In the same way you can also fix the header by changing left to top.

Thanks, 
Lovesalesforceyes


1 comment:

  1. HI, I need to freeze first 3 columns .could you please help me .Thanks in advance .

    ReplyDelete

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...