Home > Software design >  remove excess grid div without content or center the bottom grid
remove excess grid div without content or center the bottom grid

Time:10-29

i have grid container with 3 columns. However I only have 5 contents.

right now it looks like this:

|   1   |   2   |   3   |
|   4   |   5   |

I want to center the two remaining bottom div contents:

|   1   |   2   |   3   |
    |   4   |   5   |

Is this achievable or should I just create separate column for that?

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 5px;
  
}

span {
  border: 1px solid black;
}
<div >
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>

CodePudding user response:

If you want to stick with grid then what you have is a 6 column grid, each item taking up two columns and the 4th item starting at column 2 and the 5th item starting at column 4.

.container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 5px;
}

span {
  border: 1px solid black;
  grid-column: span 2;
}

span:nth-child(4) {
  grid-column: 2 / span 2;
}

,
span:nth-child(5) {
  grid-column: 4 / span 2;
}
<div >
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>

CodePudding user response:

Flexbox can do this easily.

  1. You should create 2 variables for the amounts of columns and one for the gap. That going to make the rest easier to adjust and maintain later on.
  2. Instead of grid use display: flex
  3. To allow a break to the next row after a certain amount of elements you can use the flex-wrap: wrap property.
  4. To center the child elements within that "grid" you can use justify-content: center which will center the elements along the main axis.
  5. Now the hard part is to calculate the correct width of the grid cards. For that, you can use the calc-function. The entire width is 100% from here we need to start. Then we need to subtract the gaps. The amount of gaps is columns - 1. Then we multiply the number of gaps by the gap size: (amount of gaps - 1) * gap size. That value we subtract as said from the 100% width: 100% - ((amount of gaps - 1) * gap size). Last but not least we divide that sum by the number of columns:

:root {
  --grid-columns: 3;
  --grid-gap: 5px;
}

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: var(--grid-gap);
}

.container > * {
  width: calc((100% - (var(--grid-gap) * (var(--grid-columns) - 1))) / var(--grid-columns));
}

span {
  border: 1px solid black;
  box-sizing: border-box;
}
<div >
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
</div>

  • Related