4-5 Ways to Center a div

I thought it would be a fun exercise, so here it is.

‘position: absolute’ + ‘transform’ + ‘top/left: 50%’

‘display: flex’ + ‘justify-content’ + ‘width: 100%’

‘width’ + ‘margin: auto’

display: grid + grid-template-columns

{display: grid} is another way to structure html elements.

{grid-template-columns} define the grid structure, but people typically just use bootstrap defined col classes.

{text-align} aligns text to the middle of {<p>}.

{place-items} also works if you want to set elements inside a grid child.

javascript

You can use a script to set it, but functionally it will be the same as ##1.

<script>
function SetXY() {
    var element = document.GetElementbyId("centerme");
    var x = window.innerWidth / 2;
    var y = window.innerHeight / 2;

    element.style.left = x + "px";
    element.style.top = y + "px";
    element.style.transform = "translate(-50%, -50%)";
}

window.addEventListener("load", SetXY);
</script>

<div id="centerme"></div>