Aligning a div to center of page while its position is absolute?

position: absolute;
left: 50%;
transform: translateX(-50%);

UPDATE: This is an old answer and the answer currently just below this gives a nicer solution which works even if your div has dynamic width. Another alternative, using margin: auto, can be found here, on a different, but related, question.

You can do this if you know the width of the DIV you want to centre.

CSS:

div
{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 400px;
    height: 300px;
    margin-top: -150px;
    margin-left: -200px;
}

You position the top left corner in the centre, and then use negative margins which are half of the width to centre it.

Tags:

Html

Css