skip to Main Content

I am trying to have the grid cells stay centred when I resize the window, but they end up just staying where they are rather than moving closer together. I am trying to replicate the https://rickandmortyapi.com/. I thought it might be better to share the code to my project through codepen: https://codepen.io/Alessandro-Garcia/pen/RwqNaPq

This is the code responsible for taking care of the grid:

main {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(589.19px, auto));
    gap: 0;
    overflow-x: hidden;
    justify-items: center;
    align-items: center;
}

And this is the code responsible for the individual cells:

article{
    margin: auto;
}

2

Answers


  1. You can achieve what you want using flexbox instead of grid. Try and add this on your main element.

    main {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        width: 100%;
        max-width: 2000px;
        margin: 0 auto;
    }
    

    Here is also the full example if you want to look around the code too. Rick and Morty codepen. Hope that helps! 🙂

    For further information on flexbox since you mentioned you are new to CSS have a look here.

    Login or Signup to reply.
  2. You can use justify-content: center on your grid container. CSS tricks has a good cheat sheet for grid.

    I’ve edited your codepen and literally just added justify-content: center; to main. Looks to work ok.

    Example below:

    * {
      box-sizing: border-box;
    }
    
    .container {
      display: grid;
      grid-template-columns: repeat(auto-fit, 200px);
      gap: 0.5rem;
      outline: 1px solid red;
      justify-content: center;
    }
    
    .container>div {
      width: 100%;
      background-color: gray;
      border-radius: 1rem;
      padding: 2rem;
    }
    <div class='container'>
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search