How to highlight CSS grid cells?

前端 未结 2 1627
误落风尘
误落风尘 2020-12-11 05:10

Consider a CSS grid where rows can have variable heights:

<
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 05:35

    Create elements for each grid cell:

    const grid = document.getElementsByClassName("grid")[0];
    
    const rows = 4;
    const cols = 8;
    
    for (let r = 1; r <= rows; r++) {
        for (let c = 1; c <= cols; c++) {
            const h = document.createElement("div");
            h.classList.add("highlight");
            h.style.gridRow = r;
            h.style.gridColumn = c;
            grid.appendChild(h);
        }
    }
    

    (This could also be done server side)

    And style them:

    .highlight {
      z-index: 1;
      border: 1px dashed blue;
      background: #0000FF44;
    }
    

    To show them only on hover use:

    .highlight {
        display: none;
    }
    
    .grid:hover > .highlight {
        display: block;
    }
    

提交回复
热议问题