Home > Software engineering >  CSS Grid : Colspan 2 cover the adjacent cell
CSS Grid : Colspan 2 cover the adjacent cell

Time:11-19

I have a CSS grid defined as such

.grid
  width: 100%
  height: 500px
  background-color: green
  display: grid
  grid-template-columns: repeat(6, 1fr)
  grid-template-rows: repeat(4, 1fr)
  gap: 1em
                
  > *
    background-color: gray
  
  .doubleWidth
    grid-column: span 2

  .doubleHeight
    grid-row: span 2

In this scenario, a doubleWidth class will push an item along. I would rather when a doubleWidth or doubleHeight item is in the grid, it will expand and cover the adjacent item, rather than knock it along another row/column.

In this example: https://codepen.io/dredgy/pen/XWaOebV I would like the doubleHeight item to be the first item in the second row, but as is, the doubleWidth item knocks it into the second column.

Is this possible in grid? I have previously had this working with Javascript, and with tables, but am liking this minimal solution so far.

CodePudding user response:

You could have an element inside the grid children that expands to twice the width/height of it's parent

.grid {
  width: 100%;
  height: 500px;
  background-color: green;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(4, 1fr);
  gap: 1em;
}

.grid>* {
  background-color: gray;
}

.grid .doubleWidth {
  height: 100%;
  width: calc(200%   1em);
  background-color: gray;
}

.grid .doubleHeight {
  width: 100%;
  height: calc(200%   1em);
  background-color: gray;
}
<div class="grid">
  <a>
    <div class="doubleWidth"></div>
  </a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>

  <a>
    <div class="doubleHeight"></div>
  </a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>

  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>

  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  •  Tags:  
  • css
  • Related