0

I am working with css grid at the moment, imagine I have a grid that is built in a 2x2, i.e if you have 4 child elements there would 2 rows of 2 elements. The problem I am wanting to solve if there is an odd number of children, I don't want to start the column at left the most point, is it possible to have it center align the element in the row? This I know is entirely possible with flexbox, but that is not appropriate for the end solution I am wanting.

I was hoping that css grid would have properties like,

align-items:center; justify-items:center;

The end result I am looking to achieve but struggling to is attached.enter image description here

Udders
  • 6,914
  • 24
  • 102
  • 194

1 Answers1

0

Use a 12 columns grid for instance:

Then use nth-last-child and odd to position the odd last item.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

::before,
::after {
  box-sizing: inherit;
}

.item {
  background: red;
  border: 1px solid black;
  height: 50px;
  grid-column: span 6;
}

.wrapper {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 1em;
  margin-bottom: 1em
}

.item:nth-last-child(1):nth-child(odd) {
  background: green;
  grid-column: 4 / span 6;
}
<div class="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161