Search code examples
htmlcsshtml-tablehoverborder

HTML Table with fixed header - Hover border on rows


I want to create a table in HTML with a fixed header row. Also I want the data rows to show a border when hovered. So far I have created the following

<body>
    <style>
        div {
            width: 600px;
            height: 300px;
            overflow-y: scroll;
        }
    
        table {
            height: 100%;
            width: 100%;
            border-collapse: collapse;
            position: relative;
        }
        
        .headerRow {
            position: sticky;
            top: 0;
        }
        
        th {
            position: sticky;
            top: 0;
            background-color: white;
        }
        
        .bodyRow {
        }
        
        .bodyRow:hover {
            border: 1px solid blue;
        }
    </style>
    <div>
        <table>
            <thead>
                <tr class="headerRow">
                    <th>Column 1</th>
                    <th>Column 2</th>
                    <th>Column 3</th>
                </tr>
            </thead>
            <tbody>
                <tr class="bodyRow">
                    <td>abc</td>
                    <td>def</td>
                    <td>ghi</td>
                </tr>
                <tr class="bodyRow">
                    <td>abc</td>
                    <td>def</td>
                    <td>ghi</td>
                </tr>
... many tr following
            </tbody>
        </table>
    </div>
</body>

But that is flawed. The rows are jumping because the border resizes them on hover. The jumping could be fixed by adding a transparent non-hover border to the bodyRow CSS class. But then the hover top borders are not shown anymore. Also the left side of the hover border gets drawn above the header row. You can see it when a row is half way beneath the header row.

When I use outline instead of border there is no jumping, but then there are no left and right borders/outlines. And also the top outline of the very first row is hidden beneath the header row. Is there any solution to have a fully surrounding border on hovered rows without any flaws? A solution without javascript would be strongly preferred.


Solution

  • try this, add another td as a wrapper an give it a class of border-box

       <tr class="bodyRow">
                  <td class="border-box">
                    <td>abc</td>
                    <td>def</td>
                    <td>ghi</td>
                  </td>
                </tr>
    

    then position it absolute,

     .border-box{
     width:calc(100% - 8px);
     height:calc(100% - 8px);
     position:absolute;
     top:0px;
     left:0px;
     }
    

    then target it with this

       tr:hover .border-box{
       border: 2px solid blue ;
      
       }
    

    see it working here https://codepen.io/noelosha/pen/zYJNRPX?editors=1111