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

- 3,018
- 11
- 36
- 63
-
What you tried. Did you googled? – Shakti Singh Feb 27 '11 at 09:08
-
See https://stackoverflow.com/a/34726113/3302747 has js fiddle as well – Baked Inhalf Feb 28 '18 at 14:05
6 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, usingmargin: 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.

- 5,693
- 3
- 28
- 37
Here's a simple method using percentages:
div {
width: 80%;
position: absolute;
left: 10%;
}
Simply set your desired page width, and set the left margin as half of the remainder. In this case, the width
is 80%, leaving 20%. Set left:
to 10% and it will center the div on the page.
Using this method will allow the div to scale with different window sizes and screen resolutions as well.

- 1,465
- 14
- 23
It's not possible to get HTML to automatically center anything that is absolutely positioned. Heck, HTML barely centers anything horizontally using CSS margins :-)
As the name implies absolute positioning is absolute where you get top and left fixed positions and any margins are applied relative to those positions. Auto is ignored with absolute positioning.
There are solutions using JavaScript and jQuery. Here's one that I wrote and use a lot:
jQuery .centerInClient() plugin
Hope this helps.

- 17,302
- 14
- 89
- 134
The meaning of position: absolute
is exactly that you want to specify how far from the margins of the page your div should be placed. Since you do not know the width of the screen a priori, there is no way to center it.
I guess you just want to remove the div from the page flow, while keeping it centered. In this case it may be enough to add a container div, like
<div id="external">
<div id="internal">
</div>
</div>
and the CSS
#external {
position: absolute
}
#internal {
margin: 0 auto
}
I did not test the above layout, but I think it should work.

- 20,253
- 23
- 114
- 183