Home > front end >  Display grid center child elements horizontally
Display grid center child elements horizontally

Time:02-02

I'm sure this has been answered before but I can't seem to get it working. I'm trying to horizontally center grid items with a display:grid parent. I've got a 12 column grid (76px column / 56px gap at full screen), with various column width child elements (for this example I'll just use span 8 1000px).

.main-container{
  max-width:1528px;
  margin: 0 auto;
}

.parent{
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  grid-column-gap: 56px;
  justify-items: center;
}

.grid-8{
  grid-column: span 8;
  background: red;
  opacity: 0.6;
  width: 100%;
}
<div >
  <div >
    <div >8</div>
  </div>
</div>

Also once the child element is centred is it possible for it to keep its width (1000px) until the .main-container starts to touch either side? once the browser starts to get pulled smaller (horizontally). Sorry, this is a little tricky for me to explain what I mean. The .main-container if the browser window is pulled in so this is at say 1200px wide the span 8 column will no longer be 1000px wide it will have shrunk (I'm guessing because it is relative to the main container size). But ideally, I'd like it to stay 1000px until the .main-container hits it and then the span 8 can start reducing in width.

Thanks

CodePudding user response:

You can't align items in grid automatically with justify/align props.

You can try using grid-column-end: -N; syntax for each child nodes, but it's not best way to do that.

Much better to use flex - in this case you can align child nodes as you wish.

Anyway, if you want to continue working with grid, you can do something like this (like an option):

.main-container {
  max-width: 1528px;
  margin: 0 auto;
}

.parent {
  --columns-amount: 12;
  display: grid;
  /*grid-template-columns: repeat(12, minmax(0, 1fr));*/
  grid-template-columns: repeat(var(--columns-amount), 1fr);
  grid-column-gap: 56px;
  /*justify-items: center;*/
}

.grid-8 {
  /* edit --column-size to see changes */
  --column-size: 8;
  grid-column: calc((var(--columns-amount) - var(--column-size)) / 2   1) / span var(--column-size);
  background: red;
  opacity: 0.6;
  /*width: 100%;*/
}


/* flex */

.parent--flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.parent--flex>.grid-8 {
  flex: 0 0 auto;
  width: 66.66667%;
}
<div >
  <div >
    <div >Grid</div>
  </div>
</div>

<hr />

<div >
  <div >
    <div >Flex</div>
  </div>
</div>

  •  Tags:  
  • Related