Why are only some of my CSS Grid boxes expanding when I hover over them?

前端 未结 2 1889
生来不讨喜
生来不讨喜 2021-01-12 17:11

I\'m new to grids in CSS but I want to give it a try. I have a grid with 3x3 boxes. When I hover over a box it should should out the complete row... but that\'s not working.

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 17:44

    Here is a hack to get around the jittery hovering - using display: contents to group the rows and nth-child(3n+m) to target the columns.

    Finally to show only the hovered item in a row, display property is fiddled with - see more explanations inline in the demo below:

    .container {
      display: grid;
      grid-gap: 10px;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-rows: 1fr 1fr 1fr;
    }
    
    .row {
      display: contents;
    }
    
    [class^="item"] { /* fix first column */
      grid-column: 1;
    }
    
    [class^="item"]:nth-child(3n+2) { /* fix second column */
      grid-column: 2;
    }
    
    [class^="item"]:nth-child(3n+3) { /* fix third column*/
      grid-column: 3;
    }
    
    
    [class^="item"]:hover { /* span 3 columns on hover of any cell */
      grid-column: 1 / 4;
      display: block !important; /* Show hovered item */
    }
    
    .row:nth-child(1):hover div { /* fix row on hover first row */
      grid-row: 1;
      display: none;
    }
    
    .row:nth-child(2):hover div { /* fix row on hover second row */
      grid-row: 2;
      display: none;
    }
    
    .row:nth-child(3):hover div { /* fix row on hover third row */
      grid-row: 3;
      display: none;
    }
    
    
    /* Styling */
    
    .container>.row>div {
      border: 2px solid #0580d5;
      background-color: rgba(40, 180, 240, .3);
      border-radius: 5px;
    }
    
    [class^="item"] {
      text-align: center;
      box-sizing: border-box;
      font-size: 5em;
      color: #0580d5;
      transition: .2s;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9

提交回复
热议问题