Position Elements in Center With CSS | Vertical & Horizontal

In this tutorial we will position an element in the middle of the screen with css.

Placing an element so that its position is centered horizontally is not difficult, we just need to make the text-align center, but vertically we need some tricks to do it.
Center With CSS
There are many tricks that can be used to make an element in the middle, but this time we will only try at least 2 ways to make an element right in the middle.

We start creating a div with the class container, and inside it there is another class with the name box.

The HTML structure is as follows.

Goooogle

Center div.container
First we will make the container class so that it is in the middle by adding CSS as follows

.container{
width:400px;
height:200px;
padding:20px;
background:yellow;
position: fixed;
top: 50%;
left: 50%;
margin-top: -120px;
margin-left: -220px;
}
The container class is now in the middle of the screen, it should be noted there that the value of top and left is 50%. But with settings like that, the middle position is the top left corner of the box, to adjust it we need to change the margin-top and margin-left, both of which are obtained by the following calculation.

Margin-top = height / 2 + padding

Margin-left = width / 2 + padding

However, the value must be minus (-) so that the position shifts up and to the left.

Demo 1

Center div.box
To make the box class in the middle, we will try another way, namely by adding display: table in the container class, then display: table-cell in the box class.
We add the CSS code like this.

.container{
display: table;
}
.box{
display: table-cell;
text-align: center;
vertical-align: middle;

background:orange;
border:50px solid rgba(0,0,0,.2);
}
Demo 2

Results
To complete this demo to be more complete, we add a border.
Here is the complete css code