Home > Software engineering >  CSS Grid: can I specify margin for each row of a grid?
CSS Grid: can I specify margin for each row of a grid?

Time:08-31

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.

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 >
            <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>

CodePudding user response:

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 >
  <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>
  

  • Related