Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

How can I align a DIV to the center of my page while its position is absolute? If possible without using javascript.

like image 474
Yunus Eren Güzel Avatar asked Feb 27 '11 09:02

Yunus Eren Güzel


People also ask

How do you move an absolute div to the center of a position?

If you want to center something horizontally in CSS you can do it just by, using the text-align: center; (when working with inline elements) or margin: 0 auto; (when working with block element).


2 Answers

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.

like image 184
Gareth Avatar answered Oct 20 '22 10:10

Gareth


position: absolute;
left: 50%;
transform: translateX(-50%);
like image 25
kybak Avatar answered Oct 20 '22 09:10

kybak