CODE --> CSS Published: 2019-02-28
How to align elements in the middle and center with CSS
So, one of the more difficult things to figure out, for me it was anyway, was how to align elements on in the middle and center. With CSS, this is actually very easy. Lets set up our scenario:


/*
let's say that you have a div as such
*/
div#myDiv {
background:#f1f1f1; /* Which is a little bit darker white */
border:1px solid #000000;
width:200px;
height:200px;
}




By default, this div would float to the left of the container. Now we could use margin and that would center it to the middle of the container so long as there wasn't any other div/span conflicting with it, causing it not to align to the center.

But all in all, the best way to get a div or a span or any other element for that matter to align to the center and middle of a container, is to use positioning with CSS. Absolute positioning is the best way with CSS to get elements to align to the middle and the center of the page.

So, in order to do this let's take this tiny bit of code for example:


div#myDiv {
background:#f1f1f1; /* Which is a little bit darker white */
border:1px solid #000000;
width:200px;
height:200px;
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}


Which gives us the beautiful results of:



With setting position absolute and setting the left and top to 50%, it position top 50% of the screen starting from the top on down, and the left it positions it 50% starting from the left on to the right. It's also important that you include transform:translate(-50%,-50%) otherwise you wont get an exact positioning. And that's it!
Nerd+Geek is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com.