2

I am using CSS grid for some box items. This looks good and fine but however when I make the screen smaller when there are only 2 or 1 boxes in the container its to the left how would I go about making them always in the center?

body {
  background-color: #8268EE; 
}

.item-container {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  justify-content: center;
  align-items: center;
}

.item {
  background-color: #BDD3FB;
  width: 200px;
  height: 200px;
}
<div class='item-container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>
VXp
  • 11,598
  • 6
  • 31
  • 46
cosmichero2025
  • 1,029
  • 4
  • 14
  • 37
  • Sounds like you want to use `display: flex` instead of `grid`. – Dai Jun 15 '18 at 01:13
  • No I would as of typical but some of these 'items' will take up two column slots because designer says so. So grid is necessary. I guess I should have mentioned that. – cosmichero2025 Jun 15 '18 at 01:15

2 Answers2

2

Almost there, use the justify-items property instead of justify-content:

body {
  background-color: #8268EE; 
}

.item-container {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  align-items: center;
  justify-items: center;
}

.item {
  background-color: #BDD3FB;
  width: 200px;
  height: 200px;
}
<div class='item-container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>
VXp
  • 11,598
  • 6
  • 31
  • 46
0

Actually silly me I've figured it out. All it took was justify-self: center; on the child item and it worked! I had thought when the documentation was talking about it that it was referring to the flex item inside. Then I though oh wait? You can't justify-self a flex parent that not in a flex!

cosmichero2025
  • 1,029
  • 4
  • 14
  • 37
  • How is `justify-self: center` a solution? That centers the item in its column, not across the entire row. https://stackoverflow.com/a/50239093/3597276 – Michael Benjamin Jun 15 '18 at 15:45