Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to center a grid while having it display as many items as possible within the parent element?

Looking to center a grid with 8 elements within a parent div that is a flex item. I want to be able to:

  1. Center the Grid within the parent element while displaying as many columns as the parent width allows
  2. Have the grid wrap any elements onto the next row if they don’t fit within the parent container’s constraints.
  3. Have all elements within the grid the same height

But for some reason the grid only displays 2 columns per row

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

.container {
  display: grid;
  grid-template-columns: auto auto;
  grid-auto-rows: 1fr;
  grid-gap: 20px;
  margin: auto;
}

.item {
  width: 100px;
  background: grey;
}
<div class="parent">
  <div class="container">
<div class="item">Item 1 <br/> test <br/> test</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
<div class="item">Item 8</div>
  </div>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

.parent {
  display: flex;
}    
.container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 100px);
  grid-auto-rows: 1fr;
  justify-content: center;
  width: 100%;  
}    
.item {
  background-color: green;
}
<div class="parent">
  <div class="container">
    <div class="item">Item 1 Item 1 Item 1 Item 1 Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
    <div class="item">Item 6</div>
    <div class="item">Item 7</div>
    <div class="item">Item 8</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading