Search code examples
csshtmlvertical-alignmentalignment

How can I both horizontally and vertically center two divs inside another div?



What I am trying to do should look like this:
horizontally/vertically aligned inner divs
...but my inner_top div (with the red background) is not horizontally-centered, and ends up looking like this:
all jacked up!

The conflict appears to be using display: inline-block' on the inner_top div, which is what appears to make it vertically-centered though, except for a weird spacing between the two divs.


Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <title>
            CSS sucks!!!
        </title>

        <style type = "text/css">

            #outer {
                width: 250px;
                height: 500px;
                border: 5px solid black;

                /* for vertically-centering inner divs: */
                display: table-cell;
                vertical-align: middle;
            }
                    #inner_top {
                        width: 75px;
                        height: 175px;
                        background-color: red;

                        /* horizontally-centered: */
                        margin: 0 auto;

                        /* vertically-center both this and the bottom div:
                        (but now horizontal-alignment doesn't work on this div!) */
                        display: inline-block;

                    }
                    #inner_bottom {
                        width: 150px;
                        height: 150px;
                        background-color: blue;

                        /* horizontally-centered: */
                        margin: 0 auto;
                    }
        </style>
    </head>
    <body>
        <div id = "outer">

            <div id = "inner_top">
            </div> <!-- end of inner top -->

            <div id = "inner_bottom">
            </div> <!-- end of inner_bottom -->
        </div> <!-- end of outer div -->
    </body>
</html>

Solution

  • I put your code in a jsfiddle, and it works when when I remove the display:inline-block from the top div's style.
    See http://jsfiddle.net/MrLister/5ZHdK/

    /*display: inline-block;*/
    

    Still not sure where your remark "vertically-center both this and the bottom div" comes from though; it sounds like you couldn't get it to work without the inline-block?