Highlight column on CSS grid
I need to apply an outline stroke to a column in a 3×3 CSS grid, while keeping the cells in that column separated (not merged). Is this possible with CSS grid?
Note: I can use multiple box-shadows to simulate the outline, but I’m looking for a cleaner, less hacky method.
.grid { display: grid; grid-template-areas: "cell1 cell2 cell3" "cell4 cell5 cell6" "cell7 cell8 cell9"; grid-template-columns: 100px 100px 100px; grid-template-rows: 100px 100px 100px; } .grid > div { border: 1px solid #000; }
<div class="grid"> <div class="cell1">1</div> <div class="cell2">2</div> <div class="cell3">3</div> <div class="cell4">4</div> <div class="cell5">5</div> <div class="cell6">6</div> <div class="cell7">7</div> <div class="cell8">8</div> <div class="cell9">9</div> </div>
You might need to change the order of your cell displays but the following appears to be close to what you want.
Note, it uses a combination of flexbox and grid displays and it is responsive to the size of the screen.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title> <meta charset="UTF-8"> <meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/> <!-- From: https://stackoverflow.com/questions/62799173/highlight-column-on-css-grid see also: https://codeburst.io/css-grid-layout-simple-guide-e0296cf14fe8 --> <!-- link rel="stylesheet" href="common.css" media="screen" --> <style> .wrapper { display: flex; flex-wrap: wrap; width: 80%; margin: 0 auto; } .container { display: grid; grid-template-columns: 200px; grid-template-rows: 200px 200px 200px; } .container > div { border: 1px solid #000; text-align: center; } .bdr { border: 3px solid red; } </style> </head><body> <div class="wrapper"> <div class="container"> <div class="cell1">1</div> <div class="cell2">2</div> <div class="cell3">3</div> </div> <div class="container"> <div class="cell4">4</div> <div class="cell5">5</div> <div class="cell6">6</div> </div> <div class="container bdr"> <div class="cell7">7</div> <div class="cell8">8</div> <div class="cell9">9</div> </div> </div> <script> </script> </body></html>
If you add the following you can change the border of the selected column.
<script> console.clear(); function highlite(evnt, picks) { for(var i=0; i<picks.length; i++) { picks[i].classList.remove('bdr'); } evnt.target.parentElement.classList.add('bdr'); // console.log(evnt.target.tagName+' : '+evnt.target.classList+' : '+evnt.target.parentElement.classList); } function init() { const sel = document.getElementsByClassName('container'); for (var i=0; i<sel.length; i++) { sel[i].addEventListener('click', (e) => highlite(e,sel)); } } init(); </script>