Technology with opinion

Monday, August 17, 2009

Centering a DIV within HTML

I'm by far from an HTML or DIV expert but I try to stay compliant.  One of the change to HTML 4.01 standard requires that tables no longer be used for layouts but instead only be used for grid type data.  Putting that debate aside working with DIVs is a little tricky if you have grown accustom to HTML tables.  Until recently, what has long evaded me has been centering content within HTML without a TABLE or the deprecated CENTER tag until now.

There is a trick using negative margins that does it nicely and seems to work well in FireFox & IE.  First you will need to figure out a fixed size for your DIV (a good size that you content will fit within).  Let say your DIV is 300 pixels wide, next you multiply it times -.5 which will give you your left margin of -150 pixels.  You will always position this centered DIV using 50% left.  This will center your HTML content inside the DIV horizontally.  Perform the same technique with height & top margin in order to center vertically.

This will look like the following:

See Also: W3C Standard on HTML 4.01 Tables

Tables should not be used purely as a means to layout document content as this may present problems when rendering to non-visual media. Additionally, when used with graphics, these tables may force users to scroll horizontally to view a table designed on a system with a larger display. To minimize these problems, authors should use style sheets to control layout rather than tables.

No comments: