Home > Blockchain >  How to center items within css grid columns?
How to center items within css grid columns?

Time:11-02

pen view: https://codepen.io/peter952001/pen/wvqrKwR

I am a beginner in CSS and trying to build a blog website (using Django) from scratch. I wanted to make cards responsible for each blog post on the home page like this

<div class="container">
    <div class="card-wrapper">
        <div class="card">
        <!-- Some post info -->
        </div>
    </div>
</div>

However, I am not able to make the cards centred according to their number (max is 5 per row). So, as in the pen view, I want the three cards to be centred, and if another post is added, the four get centred accordingly. Here is the css:

.card-wrapper {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    grid-gap: 10px;
    align-items: center;
    justify-content: space-around;
}
.card {
    height: 520px;
    box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    background: #fff;
    transition: all 0.5s ease;
    cursor: pointer;
    user-select: none;
    z-index: 10;
    overflow: hidden
}

I think the problem is in the grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); line but I don't know how to fix it. Thanks for help.

CodePudding user response:

You are right. The problem is in the grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); line. you can change it from absolute value to relative value. like that:

grid-template-columns: repeat(auto-fill, minmax(30%, 1fr));

.container {
    min-height: 80vh;
    padding: 20px 0;
    display: flex;
}
.card-wrapper {
    margin: 0 auto;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(30%, 1fr ));
    grid-gap: 10px;
    align-items: center;
    justify-content: space-around;
}

CodePudding user response:

add to card-wrapper

margin: 0 auto;

add to container *edit

display: flex;

  • Related