Home > Net >  CSS Grid Margin Top for entire columns
CSS Grid Margin Top for entire columns

Time:09-04

Is it possible to shift all 2nd/even grid colums as a whole like in the image using CSS grid?

enter image description here

My current situation looks like that:

display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 24px;

CodePudding user response:

You can use the :nth-child() pseudo class to achieve this. This is how I approached it:

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

.container{
  max-width: 900px;
  margin: 0 auto;
  height: auto;
}
.cards{
  display: grid;
  place-items: center;
  grid-template-columns: repeat(4,1fr);
  gap: 5px;
}

.card{
  width: 200px;
  height: 250px;
  border: 3px solid black;
}

.card:nth-child(2n-2){
  position: relative;
  top: 100px;
}
/* or use margin */
/*
.card:nth-child(2n-2){
  margin-top: 100px;
}
*/

Here is the codepen link: https://codepen.io/glenhug/pen/QWrWXJY Also this is post had a nice explanation: How to target a specific column or row in CSS Grid Layout?

CodePudding user response:

This might do the trick.

.grid-container {
  width: min-content;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;  
}

.grid-container > div {
  width: 50px;
  height: 50px;
  border: 1px solid black;
}

.grid-container div:nth-child(2n) {
  position: relative;
  top: 15px;
}
<div class='grid-container'>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
</div>

  • Related