10

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 :(

Alex
  • 66,732
  • 177
  • 439
  • 641

2 Answers2

23

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

Hristo
  • 45,559
  • 65
  • 163
  • 230
  • thanks! I found another way: make the absolute div 100%, and put inside it a relative div with `margin: 0 auto;` – Alex Apr 28 '11 at 00:33
  • @Alex... sure, but then you'd need another `
    ` element! if you want more markup, that's fine, as long as you got what you're looking for :)
    – Hristo Apr 28 '11 at 00:37
  • 1
    I like this solution better: http://stackoverflow.com/questions/1776915/how-to-center-absolute-element-in-div You don't have to know the size. – Scotty Waggoner Jun 26 '13 at 00:53
12

Just subtract the window midpoint from half the width of you element on resize. Here's a simple plugin that you could easily accomodate to center vertically if need be as well:

$.fn.centerMe = function () {
    this.css('left', $(window).width()/2 - $(this).width()/2);
};

$(window).resize(function() { $('#yourElem').centerMe(); });

$('#yourElem').centerMe();

See working example →

mVChr
  • 49,587
  • 11
  • 107
  • 104