如何在水平和垂直方向上将两个div放在另一个div中?

时间:2013-06-12 19:31:36

标签: css html vertical-alignment alignment


我想要做的应该是这样的:
horizontally/vertically aligned inner divs
...但我的inner_top div(红色背景) 水平居中,最终看起来像这样:
all jacked up!

冲突似乎是在display: inline-block' div上使用inner_top,这似乎使得垂直居中,除了两个div之间的奇怪间距。

<小时/> 这是我的代码:

<!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>

3 个答案:

答案 0 :(得分:2)

我把你的代码放在一个jsfiddle中,当我从顶部div的样式中删除display:inline-block时,它就有用了。
http://jsfiddle.net/MrLister/5ZHdK/

/*display: inline-block;*/

仍然不确定你的评论“这个和底部div的垂直中心”来自哪里;听起来如果没有内联块你就无法工作?

答案 1 :(得分:1)

只需使用这个简单的css块

来居中
#inner_top {
  margin-left: auto;
  margin-right: auto;
}
#inner_bottom {
  margin-left: auto;
  margin-right: auto;
}

答案 2 :(得分:0)

您需要对要尝试居中的所有子元素使用margin:0 auto

margin:0 auto的儿童不能是街区类型。

http://jsfiddle.net/EDpgS/