thinking stiff

Highlight <table> column on :hover using CSS with no Javascript

Posted in Programming by thinkingstiff on 2012/06/26

While HTML allows the :hover pseudo-class on <tr> elements, unfortunately the same does not hold true for <col> elements. All solutions I’ve seen to highlight columns in tables involve Javascript.

I’ve tried to solve this with CSS a couple of times before with no luck. I recently saw this question on Stackoverflow, cols, colgroups and css :hover psuedoclass, which was looking to highlight both rows and columns at the same time. I gave it a shot and was able to do it using the ::after pseudo-element and no Javascript.

I saw another question looking for just a column solution, html: hover table column, and I simplified the code to what you see below. This works in all modern browsers except Firefox, which requires a little tweak. The function firefoxFix() below takes care of this.



table {
    border-spacing: 0;
    border-collapse: collapse;
    overflow: hidden;
    z-index: 1;

td, th, .ff-fix {
    cursor: pointer;
    padding: 10px;
    position: relative;

.ff-fix:hover::after {
    background-color: #ffa;
    content: '\00a0';
    height: 10000px;
    left: 0;
    position: absolute;
    top: -5000px;
    width: 100%;
    z-index: -1;



Firefox Fix:

function firefoxFix() {

    if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {

        var tds = document.getElementsByTagName( 'td' );

        for( var index = 0; index < tds.length; index++ ) {
            tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';                     

        var style = '<style>'
            + 'td { padding: 0 !important; }' 
            + 'td:hover::before, td:hover::after { background-color: transparent !important; }'
            + '</style>';
        document.head.insertAdjacentHTML( 'beforeEnd', style );


Tagged with: , , ,
%d bloggers like this: