tags:

views:

267

answers:

2

I'm trying to get consistent centering cross browser when I set the position property of the parent element to relative and the position of the child to absolute (the child is the element I'm trying to center)

Currently in firefox it's not exactly center, but ie6/7 it is (sample of what i'm using below)

#wrapper { min-width:995px; position: relative; }
#wrapper2 { margin:0 auto; z-index: 0; position: absolute; }
+3  A: 

Are you trying to horizontall center, vertically center or both?

In either case use of margin and absolute is incompatible. Position absolute takes it out of the normal flow. If you take out the position absolute the inner div is horizontally centered correctly.

Whatever you want to do, centering (especially vertical centering) is a huge problem in pure CSS, particularly if IE6 support is required.

If you must use absolute positioning on the inner div, you pretty much need to rely on pixel positioning, which means knowing the fixed sizes of the outer and inner divs (barring a few corner cases).

cletus
+1  A: 

If you're interested in a jQuery approach, I used the following a few weeks ago:

$(window).load(function() {
    $("ul.recent-list div img").each(function() {
     var moveX = ($(this).width() / 2 * -1) + 18;
     var moveY = ($(this).height() / 2) * -1 - 18; // 18 is 1/2 the default offset of 36px defined in CSS
     $(this).css({'top' : moveY, 'left' : moveX});
    });
});

I had to take an image of an unknown size and position it within a "window" of 36x36px so that only the 36 square px area of the image was visible through the window <div>.

The (window).load was needed instead of (document).ready because Safari cannot use the width() and height() functions if no width/height attributes are defined on the image on document.ready. Since my images were of varying dimensions, I had to use window.load instead.

Mark Hurd