skip to Main Content

i have created a dynamic grid. That is placing as many columns as possible. The only porblem is, that the widht need to be set. in my example i have it set to 100%.
That is generating a white space around the grid that can’t befilled with a column.

is there any way to center the grid in the div or make the width as wide as the available columns?

that my current css for the grid:

.card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, calc(235px + 30px));
    width: 100%;
    height: 100%;

    place-items: center;
    grid-auto-rows: calc(325px + 30px);
}

and thats the html:

<div className="card-grid">
    <h1>some Content</h1>
    <h1>some Content</h1>
    <h1>some Content</h1>
    <h1>some Content</h1>
    <h1>some Content</h1>
    <h1>some Content</h1>
    <h1>some Content</h1>
</div>

in the browser it looks like this:
enter image description here

And i want to remove the space that is overlapping on the right side.
Setting the width on auto doesn’t work bc. then the grid has only on column.

2

Answers


  1. Try using justify-items and align-itmes separately instead of place-items

    .card-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, calc(235px + 30px));
      grid-auto-rows: calc(325px + 30px);
      justify-content: center;
      align-items: center;
    }
    
    Login or Signup to reply.
  2. You can do it this way

    <script type="text/javascript">
    
     function gridhandle(){
     var w = window.innerWidth;
     var items = document.querySelectorAll('.card-grid h1');
     var elwidth = 355;
     var itcount = items.length * elwidth > w? w / elwidth : items.length;
     var grid = document.querySelector('.card-grid');
     grid.style['grid-template-columns'] = 'repeat(' + Math.round(itcount) + ',1fr)';
     }
    
    window.addEventListener("resize",gridhandle);
    gridhandle();
    
    </script>
    

    elwidth is the width you want to set for the width of the item

    var elwidth = 355;
    

    the resize event adjusts the amount of element to display per row depending on the width of the browser

    window.addEventListener("resize",gridhandle)
    

    this script should be placed at the end of the body, after loading the dom

    <body>
    <div class="card-grid" ... >
    ....
    </div>
    
      <script .... >
    
      ........
      </script>
    </body>
    

    css

    .card-grid{
     display;grid;
     place-items:center;
     grid-auto-rows:calc(325px + 30px);
    }
    

    You can try with 1,2 3… the elements will always be centered

    you can replace the selector

    ('.card-grid h1')
    

    by

    ('.card-grid > *')
    

    and you can place inside the div any type of element

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search