Search code examples
htmlgroupingcell

Is there any way to visually group cells in a table?


Is there any way to achieve the following in HTML:

table with visually grouped cells

The idea is to generate a tabular grid with some 'related' items visually grouped.

From my current understanding, there is no way to do this with plain html tables(?), but I am wondering if the effect can be achieved with CSS grids, javascript, canvas, or even SVG. The simpler the better, of course!

I am trying to modernise some HORRID, ugly, slow-as-all-heck PDF code.

The PDF achieves this by getting the bounds of the various cell elements and then creating and positioning a single big filled rect behind them.

As you might guess, the point of this is to generate printed reports, so responsiveness is not a requirement. That said, I'd love to avoid positioning everything absolutely if I can...that would probably be too fragile/fiddly code.

I'm familiar with all the technologies I've mentioned but I've never had to try this specific thing before and it 'feels' like I'm pushing boundaries here...hence I'm asking before trying to dive in and (possibly/probably futilely) hack.

Thoughts/suggestions/pointers gratefully accepted.


Solution

  • I would use a CSS-Grid and then do the highlighting by adding classes to those elements that have a box-shadow with the size offset that equals half to that of the gap:

    .d-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-gap: 10px;
      padding: 5px;
    }
    
    .hl-green {
      box-shadow: 0 0 0 5px green;
    }
    
    .hl-blue {
      box-shadow: 0 0 0 5px blue;
    }
    
    /* for visualisation pupose only */
    .d-grid > div {
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 15vh;
      border: 1px solid black;
    }
    <div class="d-grid">
      <div>A</div>
      <div class="hl-green">B</div>
      <div class="hl-green">C</div>
      
      <div>A</div>
      <div class="hl-green">B</div>
      <div class="hl-green">C</div>
      
      <div>A</div>
      <div>B</div>
      <div>C</div>
      
      <div class="hl-blue">A</div>
      <div class="hl-blue">B</div>
      <div>C</div>
      
      <div>A</div>
      <div>B</div>
      <div>C</div>
    </div>