How can I align
a DIV
to the center of my page while its position
is absolute
? If possible without using javascript.
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).
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.
position: absolute;
left: 50%;
transform: translateX(-50%);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With