Home > Software engineering >  Arrange columns of two different grids with gaps in line
Arrange columns of two different grids with gaps in line

Time:02-08

How do I get the two grid cells "right" and "col" in a line below each other without adjusting the HTML? Without gaps this is not a problem, but as soon as gaps are added, the columns are no longer in line.

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer {
  display: grid;
  column-gap: 32px;
  grid-template-columns: 1fr 3fr;
}

.Col4Grid {
    display: grid;
    column-gap: 32px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
}


.Col {
  background-color: #e7e7e7;
}
<div >
  <div >
    left
  </div>
  <div >
    right
  </div>
</div>

<div >
  <div >col</div>
  <div >col</div>
  <div >col</div>
  <div >col</div>
</div>

CodePudding user response:

I hope I got your intended layout correct. Just apply the same grid-column rule to both containers. then let the column (right) span 3 columns with: grid-column: span 3;

*, *::before, *::after {
  box-sizing: border-box;
}

.OuterContainer,
.Col4Grid {
  display: grid;
  column-gap: 32px;
  grid-template-columns: repeat(4, 1fr);
}

.Col {
  background-color: #e7e7e7;
}

.OuterContainer .Col:nth-child(2) {
  grid-column: span 3;
}
<div >
  <div >
    left
  </div>
  <div >
    right
  </div>
</div>

<div >
  <div >col</div>
  <div >col</div>
  <div >col</div>
  <div >col</div>
</div>

CodePudding user response:

Another more "dirty math" result. Just change the variable to whatever size you need.

*,
*::before,
*::after {
  box-sizing: border-box;
}

:root {
 --g-gap: 40px;
}

.OuterContainer {
  display: grid;
  column-gap: var(--g-gap);
  grid-template-columns: 1fr 3fr;
}

.Col4Grid {
  display: grid;
  column-gap: var(--g-gap);
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

.Col {
  background-color: #e7e7e7;
}

.Col4Grid .Col:first-child {
width: calc(100%   1/2*var(--g-gap));
}

.Col4Grid .Col:not(:first-child) {
margin-left: calc(1/2*var(--g-gap));
}
<div >
  <div >
    left
  </div>
  <div >
    right
  </div>
</div>

<div >
  <div >col</div>
  <div >col</div>
  <div >col</div>
  <div >col</div>
</div>

This is of course not responsive (if you intend to use 100 px) and definitely not a good way to solve this, but I thought it is a funny way to tweak things!

  •  Tags:  
  • Related