1

I have a div with n (can be different number) children. I want to display them in one row and center horizontally.

In flex, I would do:

display: flex;
justify-content: center;

How is it possible to do it with grid, without flex?

.a {
  height: 20px;
  width: 20px;
  background: blue;
  border: 1px solid red;
}

.b {
  display: grid;
  gap: 20px;
}
<div class="b">
  <div class="a">x</div>
  <div class="a">x</div>
  <div class="a">x</div>
  <div class="a">x</div>
</div>
underfrankenwood
  • 431
  • 1
  • 7
  • 22

1 Answers1

0

Here are all the elements in one row, centered:

.a {
  height: 20px;
  width: 20px;
  background: blue;
  border: 1px solid red;
}

.b {
  display: grid;
  justify-items: center;
  gap: 20px;
  grid-auto-columns: 1fr;
  grid-auto-flow:column;
}
<div class="b">
  <div class="a">x</div>
  <div class="a">x</div>
  <div class="a">x</div>
  <div class="a">x</div>
</div>

Update: you can use a 'container' element to center the grid.

.a {
  height: 20px;
  width: 20px;
  background: blue;
  border: 1px solid red;
}

.b {
  display: inline-grid;
  justify-items: center;
  gap: 20px;
  grid-auto-columns: max-content;
  grid-auto-flow:column;
}
.c {
  text-align: center;
}
<div class="c">
  <div class="b">
    <div class="a">x</div>
    <div class="a">x</div>
    <div class="a">x</div>
    <div class="a">x</div>
  </div>
</div>
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25