hasLayout.net

No Auto Margin Center Pseudo-Bug

Affected Versions

This bug affects: IE8, IE7

Symptoms

side margins set to value `auto` do not center a block-level element

Date of the Tutorial

Sun Aug 9 06:28:29 2009

Description

So you're hacking away your precious little page... set left and right margins to value auto along with proper width; everything's spiffy in all the browsers but IE. What gives? Let's glance at the demo

Demo

HTML Code:
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>No Auto Margin Center Bug - hasLayout.net by Zoffix Znet</title>
<h1>Center Meh!</h1>
CSS Code:
h1 {
    width: 100px;
    margin: 0 auto;
}

The reason I called this bug "pseudo-bug" is because people who know what they are doing (providing they haven't been awake for 27 hours straight and did not abuse any substances) will never come across this "bug". In fact, this isn't really a bug in the affected versions so much as it's the affected versions rendering as their older relatives. Spotted the problem yet?

Solutions

Below are solutions for the above bug ordered by the solution type.

Solution (Pseudo Bug)

Date of the Solution

Sun Aug 9 06:42:54 2009

Fixed Versions

All of the affected

Description

If you have a sharp eye, you probably spotted the problem already - no DOCTYPE! What does this mean? Affected IEs go into quirks mode and start rendering like their old ancestors because they think your page was coded long time ago and isn't ready for the newer, less buggy rendering.

HTML Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>No Auto Margin Center Bug Fixed Demo - hasLayout.net by Zoffix Znet</title>
<h1>Center Meh!</h1>
CSS Code:
h1 {
    width: 100px;
    margin: 0 auto;
}

We've added the doctype and now everything works as it should. Keep in mind that having comments and other junk before the doctype can also trow IE in quirks mode. A simple test to see which mode your page is in, simply run this code in your location bar: javascript:alert(document.compatMode). If the message says BackCompat, it means quirky behaviour.