How center vertically and horizontally element in CSS?

In Internet is a lot of information about centering  in CSS. But it is difficult find something about simple centering elements on the website, both horizontal and vertical. In this post I describe you step by step how centering any element in body tag.

So, open your favorite editor for html code and paste this code:



How center vertical and horizontal element in CSS ?

body {     margin:0; padding:0;     }
.container {
                   background-color:#aaa;
                   position: absolute;
                   width: 600px;
                   height: 300px;
                }


   

I name my file: center.html.

In the first css line define zero for margin and padding of body element. Next step create div element with container class. In css style for this class determine background-color as dark gray. This element must be have the absolute position. The width this div element set on 600 px and height on 300 px.

If you run this site see rectangle in the left-top corner.

How center this rectangle in horizontal and vertical?

First value for margin property is top, another right and bottom and left. So set left margin on half width element and top on half height element. Paste this line into style for container class:

margin: 150px 0 0 300px;

When you run center.html file you see:

Move this element in the opposite direction. The opposite direction is the minus sign before number. So change this margin properties on:

margin: -150px 0 0 -300px;

Run your website.

Here You must either move element to about 50% its width and heigth. So write left and top property for div element as 50%.

left: 50%;
top: 50%;

Run your website:

Even you resize window, this element will be in the middle website.

Of course, you must know width and height your element and this element must have absolute position.