How to center with CSS

Everything you need to know about vertical and horizontal centering with CSS. No need for scripting or tables :)

CSS: How to horizontal center an image or text:

{ text-align: center; } centers inline elements horizontally within their block containers.

how to center an image with CSS

Centered text

    <img src="image.jpg" alt="alternative text" />
    <p>Centered text</p>

    img, p { text-align:center; }
    

CSS: How to horizontal center a menu with a fixed width:

{ margin: auto; } centers block elements horizontally within its container.

    <ul>
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
    </ul>

    ul { margin:0 auto; width:400px; }
    li { float:left; width:33,3%;}
    

CSS: How to horizontal center a menu with an unknown width:

    <ul>
        <li><a href="#">First item</a></li>
        <li><a href="#">Item in the middle</a></li>
        <li><a href="#">Last item, no more items</a></li>
    </ul>

    ul, li { float:left; position:relative; }
    ul { left:50%; }
    li { right:50%; }
    

CSS: How to vertical center an image or text with a fixed height:

Remember the "good" old table days where vertical alignment was easy? It's still easy or let's say possible. The trick is to get an element behave like a table element.
That's possible by using the display element, { display: table/table-cell; }, but IE 6-7 sadly doesn't support it why we have to do IE 6 and 7 specific markup and styling :(

    <ul>
        <li>
            <a href="#">
                <span>Vertical<br />centered<br />text</span>
                <!--[if lte ie 7]><b></b><![endif]-->
            </a>
        </li>
        <li>
            <a href="#">
                <span>Line one<br />Line two<br />Line three</span>
                <!--[if lte ie 7]><b></b><![endif]-->
            </a>
        </li>
        <li>
            <a href="#">
                <span>Only two<br />lines here</span>
                <!--[if lte ie 7]><b></b><![endif]-->
            </a>
        </li>
    </ul>

    ul { margin:0 auto; width:400px; }
    li { float:left; }
    a { display: table; height: 100px; }
    span { display: table-cell; vertical-align: middle; }

    IE 6 + 7 Styling:
    span { display: inline-block; }
    b { display: inline-block; height: 100%; vertical-align: middle; }
    

CSS: How to vertical and horizontal center a background image:

    <div class="bg"></div>

    .bg { background: url('image.jpg') center center no-repeat; }
    
Back to blog post (DK)