3 ways to centre a div + life advice

3 ways to centre a div + life advice

A few years ago, when I was a beginner developer such a task, to centre a div, would be easy and hard at the same time. It's super comprehensible yet you're not sure how to do it (although you probably saw it many times while following a boot camp). And then googling starts and we all know how it goes.

What I want you to know is that this is totally fine! Not knowing something is okay, no matter how simple (or hard) it may look. On the other, what needs to be stressed out is the ability to find the answer (it is also a skill, treat it that way). That is the key! Now, when I'm googling, I kinda feel where (or if) the answer lies on a certain page. You'll get there, keep it up!

Now, let's centre this DIV:

<section>
    <div class='centre'>
        test
    </div>
</section>

The Traditional Approach

.centre {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

And then flexbox came

.centre {
    display: flex;
    justify-content: center;
    align-items: center;
}

With Grid 🔥

.centre {
    display: grid;
    place-items: center;
}

Till next time, Dalibor

 
Share this