tags:

views:

515

answers:

3

I need to place the div (absolute) element in the center of my window. But i am having problems doing so, because the width is unknown

I tried this. But it need to be adjusted because the width is changing.

.center {
      left: 50%;
      bottom:5px;
}

Please help,

Thanks

+3  A: 

As far as I know, this is impossible to achieve for an unknown width.

You could - if that works in your scenario - absolutely position an invisible element with 100% width and height, and have the element centered in there using margin: auto and possibly vertical-align. Otherwise, you'll need Javascript to do that.

Pekka
+1 for the "margin: auto" thing. I've tried this before to horizontally centre a div using the line "margin: 0 auto" - the "0" applying to the vertical margins and the "auto" the horizontal. I think this is what StackOverflow uses for the very top level div to get the 2 thick white borders down the sides of the page. However, the W3Schools page on CSS margin states for the auto value that "The result of this is dependant of the browser" - I've not personally tried it across many different browsers, so I can't really comment on this point (but it obviously does the trick in some of them)
Steg
+1  A: 

Heres a useful jQuery plugin to do this. Found here. I don't think it's possible purely with CSS

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
      var el = $(this);
      var h = el.height();
      var w = el.width();
      var w_box = $(window).width();
      var h_box = $(window).height(); 
      var w_total = (w_box - w)/2; //400
      var h_total = (h_box - h)/2;
      var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
      el.css(css)
    });
};
Ben Shelock
+5  A: 
<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>
bobince
Its simple to understand and working, tyvm :)
Ish Kumar