Skip to content

Centering things is hard

Published on .
At 361 words, this article should take about 2 minutes to read.

Introduction

Everyone knows the hardest thing in frontend development is centering something within an element.

Define the problem

There's just so many options these days, I get decision paralysis!

Table

<div class="parent">
<div class="child">
Centered!
</div>
</div>

<style>
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 25rem;
height: 25rem;
background-color: pink;
}

.child {
width: 10rem;
height: 10rem;
margin: auto;
background-color: rebeccapurple;
}
</style>

Absolute position

<div class="parent">
<div class="child">
Centered!
</div>
</div>

<style>
.parent {
position: relative;
width: 25rem;
height: 25rem;
background-color: pink;
}

.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 10rem;
height: 10rem;
background-color: rebeccapurple;
}
</style>

Flex

<div class="parent">
<div class="child">
Centered!
</div>
</div>

<style>
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 25rem;
height: 25rem;
background-color: pink;
}

.child {
width: 10rem;
height: 10rem;
background-color: rebeccapurple;
}
</style>

Grid

<div class="parent">
<div class="child">
Centered!
</div>
</div>

<style>
.parent {
display: grid;
place-items: center;
width: 25rem;
height: 25rem;
background-color: pink;
}

.child {
width: 10rem;
height: 10rem;
background-color: rebeccapurple;
}
</style>

JavaScript

<div class="parent">
<div class="child">
Centered!
</div>
</div>

<style>
.parent {
width: 25rem;
height: 25rem;
background-color: pink;
}

.child {
width: 10rem;
height: 10rem;
background-color: rebeccapurple;
}
</style>

<script>
// get the parent and child
var parent = document.querySelector(".parent");
var child = document.querySelector(".child");

// get the parent dimensions
var parentWidth = parent.offsetWidth;
var parentHeight = parent.offsetHeight;

// get the child dimensions
var childWidth = child.offsetWidth;
var childHeight = child.offsetHeight;

// calculate the position of the child
var leftPosition = (parentWidth - childWidth) / 2;
var topPosition = (parentHeight - childHeight) / 2;

// set the position of the child
child.style.left = leftPosition + "px";
child.style.top = topPosition + "px";
</script>

Define the solution

The obvious answer to this problem is to ask ChatGPT, right…?

Actually, there's a much simpler way. Since all developers use VS Code, simply install this extension that solves the problem for you.

Conclusion

This is a joke. Learn CSS.


Fin

Comments

In almost all cases, the comments section is a vile cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on CalcKey (which is not a vile cesspool of Reply Guys, racists, and bots).