Search code examples
htmlcssmargin

How to center container using margin: auto


For some reason, margin:auto is not working.

HTML

<body>
    <div id="background">
        <div id="header">
            <div id="title">Welcome</div>
        </div>
    </div>
</body>

CSS

#background {
    min-width: 960px;
}

#title {
    display: block;
    margin: auto;
    background-color: blue;
}

This just just draws a blue line across the top of the screen with the word 'Welcome' on the left. Why isn't my margin:auto working?


Solution

  • The correct syntax for horizontally centering via margin is: margin: 0px auto; as this will set the left and right margin to auto. You need to set a width on it if you use this approach, because the width is 100% by default.

    Alternatively, you can also use text-align:center if you are just centering text.

    Working jsFiddle using text-align:center.

    Alternative jsFiddle.. I don't know what style you are trying to achieve.