在中心容器内水平对齐div

时间:2014-05-08 15:30:25

标签: html css alignment sidebar

如何在css中将4个div对齐到容器内,如下图所示:http://postimg.org/image/w0k7wgdfb/ 这是我的HTML,我想我需要另一个容器用于DIV#2和DIV#3。

<div id="container">
   <div id="header"> DIV 1 </div>
    <div id="wraper"> <!-- WRAPER -->
      <div id="sidebar"> DIV 2 </div>
      <div id="content"> DIV 3 </div>
    </div> <!-- WRAPER -->
   <div id="footer"> DIV4 </div>
</div>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

Solution 1 - Floats

在对齐内容后,您可以使用一个简单的浮动技巧来处理两个中间div:

CSS

html, body {
    height: 100%;
    width:100%;
    margin: 0;
    padding: 20px;
    box-sizing:border-box;
}
#container {
    text-align:center;
    width:500px;
    margin: 0 auto;
    height:100%;
    background:black;
    padding:20px;
    box-sizing:border-box;
}
#header {
    background:green;
    height:20%;
}
#wraper {
    height:60%;
    overflow:hidden;
}
#sidebar {
    width:20%;
    float:left;
    height:100%;
    background:red;
}
#content {
    overflow:hidden;
    background:blue;
    height:100%;
}
#footer {
    background:orange;
    height:20%;
}

Solution 2 - Display:Table

在居中对齐内容后,您可以将表格布局应用于中间div

CSS

html, body {
    height: 100%;
    width:100%;
    margin: 0;
    padding: 20px;
    box-sizing:border-box;
}
#container {
    text-align:center;
    width:500px;
    margin: 0 auto;
    height:100%;
    background:black;
    padding:20px;
    box-sizing:border-box;
}
#header {
    background:green;
    height:20%;
}
#wraper {
    height:60%;
    display:table;
    width:100%;
}
#sidebar {
    width:20%;
    display:table-cell;
    background:red;
}
#content {
    display:table-cell;
    background:blue;
}
#footer {
    background:orange;
    height:20%;
}

答案 1 :(得分:0)

Here有一个工作小提琴 HTML

                     

CSS

 #one{
        width: 400px;
        background: black;
        margin: 0 auto;
        height: 600px;
    }
    #two{
        height: 100px;
        width: 400px;
        background: lime;
    }
    #three{
        height: 400px;
        width: 100px;
        background: yellow;
        float: left;
    }
    #four{
        height: 400px;
        width: 300px;
        background: blue;
        float: left;
    }
    #five{
        height: 100px;
        clear: both;
        width: 400px;
        background: silver;
    }