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

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

+6
html css
source share
6 answers

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

CSS

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

You position the upper left corner in the center, and then use the negative margins, which are half the width, to center it.

+17
source share
 position: absolute; left: 50%; transform: translateX(-50%); 
+6
source share

Try the following:

 position: absolute; width: 600px; left: 50% margin-left: -300px; 
+5
source share

It is not possible to force HTML to center everything that is absolutely positive. Heck, HTML barely centers anything horizontally using CSS fields :-)

As the name implies, absolute positioning is absolute when you get top and left fixed positions, and any fields apply to those positions. Auto is ignored with absolute positioning.

There are solutions using JavaScript and jQuery. Here I wrote and used a lot:

jQuery.centerInClient () plugin

Hope this helps.

0
source share

The value of position: absolute is exactly what you want to indicate how far from the page margins 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 think you just want to remove the div from the page stream, keeping it in the center. In this case, it may be sufficient to add a div container, for example

 <div id="external"> <div id="internal"> </div> </div> 

and CSS

 #external { position: absolute } #internal { margin: 0 auto } 

I have not tested the above layout, but I think it should work.

0
source share

Here's a simple method using percentages:

 div { width: 80%; position: absolute; left: 10%; } 

Just set the desired page width and set the left margin as half of the rest. 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 various window sizes and screen resolutions.

0
source share

All Articles