Search code examples
cssbrowser-support

Browser support for margin: auto


Like many designers I use margin: 0 auto; to center an element. While trying to check the browser support for this feature at http://www.caniuse.com I was unable to find anything related.

Is there a browser compatibility matrix for this feature?


Solution

  • Although you probably don't want to adjust your code to work in antique browsers that don't support margin: 0 auto;, but since you asked:

    Support started only with IE6. If you want to support earlier browsers, you can add text-align: center; to the parent element. This works because old browsers incorrectly apply text-align also to block-elements. At the same time, keep margin: 0 auto; for modern browsers. If you want text-align: center to work in modern browser as well, you can also set display: inline-block; - then you won't need margin: 0 auto;.

    So assuming this is your HTML:

    <div id="outer">
        <div id="inner"></div>
    </div>
    

    you have these options:

    Option 1

    #outer {
        background: pink;
        width: 100%;
        text-align: center; /* for very old browsers */
    }
    
    #inner {
        background: green;
        display: inline-block;
        width: 50px;
        height: 50px;
        margin: 0 auto; /* for >99% of browsers */
    }
    

    Option 2

    #outer {
        background: pink;
        width: 100%;
        text-align: center;
        height: 50px; /* height of child - necessary for IE8 and IE9,
        otherwise the height is slightly larger than that of the child */
    }
    
    #inner {
        background: green;
        display: inline-block; /* necessary for modern browsers, IE8+ */
        width: 50px;
        height: 50px;
    }
    

    But as I said, before supporting such ancient browsers, you may really think if the extra effort is worth it, or if it's better to just drop support for them.