0

It's strange that CSS grid doesn't have properties that can do this easily (my codepen here: https://codepen.io/Chiz/pen/dydeZpz).

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-gap: 20px;
  align-items: center;
  justify-content: center;
}

.container div {
  background-color: gray;
  height: 100px;
}
<div class="container">
  <div>Box 1</div>
  <div>Box 2</div>
  <div>Box 3</div>
  <div>Box 4</div>
</div>

If I use align-self: center and justify-self: center inside the .container div part, it shrinks the sizes of the boxes down to the size of the content.

Shouldn't CSS grid have properties such as grid-item-align:top center sort of thing? I'm trying not to use 90s CSS hacks to do this cos' that would defeat the purpose of CSS grid.

With flexbox, it's far easier to align things where I want.

Sigurd Mazanti
  • 2,098
  • 1
  • 8
  • 24
Xeon
  • 385
  • 3
  • 11

2 Answers2

1

flex and grid works wonderfully together. Just apply your flex-positioning properties on the item you want.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-gap: 20px;
  align-items: center;
  justify-content: center;
}

.container div {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: gray;
  height: 100px;
}
<div class="container">
  <div>Box 1</div>
  <div>Box 2</div>
  <div>Box 3</div>
  <div>Box 4</div>
</div>
Sigurd Mazanti
  • 2,098
  • 1
  • 8
  • 24
0

You could use flexbox on the items, while using grid on the container. Since flexbox is generally more used to align anything.

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-gap: 20px;
  align-items: center;
  justify-content: center;
}

.container div {
  background-color: gray;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div>Box 1</div>
  <div>Box 2</div>
  <div>Box 3</div>
  <div>Box 4</div>
</div>