Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css/ jQuery - center absolute positioned div

The div is 50% opaque and is displayed on top of the site's content, and it has a fixed width of 960 pixels (it's created by jQuery).

How can I center it horizontally?

margin: 0 auto; doesn't work :(

like image 221
Alex Avatar asked Apr 27 '11 23:04

Alex


1 Answers

margin: 0 auto; won't work for elements that are absolutely positioned. Instead, we can work with the properties of the element itself. Check out the fiddle...

http://jsfiddle.net/UnsungHero97/HnzyT/2/

To center it horizontally is easy since you know the width AND its positioned absolutely. All you have to do is give it 2 CSS properties:

width: 960px;
position: absolute;

/* ... other CSS properties... */

left: 50%; /* 1. move it to the right 50% of the width of the page; now the left side of the element is exactly in the middle */
margin-left: -480px; /* move the element to the left exactly half of its width and now the center of the element is centered horizontally */

If you want to center it both vertically and horizontally, you need to know how wide AND how tall the element is.

I hope this helps.
Hristo

like image 135
Hristo Avatar answered Oct 04 '22 16:10

Hristo