css html

Centering absolutely positioned elements

Having problems setting auto margins on an absolutely positioned element? Me too… until I found that I was missing one simple bit of css.

When centering an absolutely positioned element horizontally you have to specify the left and right properties as zero for this to work!

I found the solution here but I thought I’d note it down for all those people that may not have come across this themselves. Somehow it seems to have passed me by…

Auto-margins can center an absolutely positioned element inside its containing block.

For this to work, you have to

  • specify the offset properties (of opposite sides) with same values, i.e. by setting left:0; right:0; for horizontal centering and top:0; bottom:0; for vertical centering,
  • set dimensions along the axis you want to center along,
  • enable auto-margins along the axis you want to center along.

Internet Explorer note: IE6 can not relate absolutely positioned elements to opposite sides of containing block, so only one of the offset properties is used. This brings the element out of balance and renders auto-margins useless.

I hope someone finds this useful…

Leave a Reply

Your email address will not be published. Required fields are marked *