Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS Grid: can I specify margin for each row of a grid?

Lets say I have a grid of elements like this, this is simple CSS grid

Lets say I have

Any way I can set margin for the second row of this grid like this?
I’ve tried to control elements via nth-child, but it messed up first row.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 0px;
  grid-row-gap: 0px;
  overflow-x: scroll;
  margin: 0 -18px 10px;
  gap: 14px;
  width: auto;
  height: auto;
  padding: 13px 0;
}

.item {
display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 146px;
  width: 130px;
  background-color: #f0f0f0;
  border-radius: 27px;
  text-align: center;
  letter-spacing: 0px;
  color: #082b26;
  opacity: 1;
  padding: 0 20px;}
          <div class="wrapper">
            <div class='item'>1</div>
            <div class='item'>2</div>
            <div class='item'>3</div>
            <div class='item'>4</div>
            <div class='item'>5</div>
            <div class='item'>6</div>
          </div>

>Solution :

It is only possible if you know the exact amount of columns. Then you can target the elements of the 2nd row with nth-child and add a margin to them to offset them from their normal placement.

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 20px;
  padding: 50px;
}

.grid > div:nth-child(n+4):not(:nth-child(n+7)) {
  margin-left: 50px;
  margin-right: -50px;
}



/* for vizualisation only */
.grid > div {
  border: 1px solid black;
  height: 20vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
</div>
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading