如何将两个并排的div居中?

时间:2014-09-23 09:56:17

标签: html css

我想把Div #Content& #Sidebar,这是我的代码,有人可以解释我会如何做到这一点,因为Divs是并排的吗?

我已更新现有帖子以提供更多信息 - 谢谢!

<body>
    <div id="wrapper">

        <div id="header">
            <div class="header">Title of Website</div>
        </div>

        <div id="menu">
            <div class="menu"><img src="images/menusample.png" alt="sample of js menu"></div>
        </div>

        <div id="content">Main content</div>

        <div id="sidebar">Sidebar/Widget</div>

        <div id="footer">Footer</div>

    </div>
</body>

的style.css:

    body {
    margin:0px 0px 0px 0px;
    background-image:url('images/nifla-bg.png');
    font-family: 'Source Sans Pro', sans-serif;
    font-size:16px;

}

#wrapper {
    width:100%;
    height:auto;
    margin:0 auto;
}

#header {
    width:100%;
    height: 90px;
    clear: both;
    margin: 0 auto;
    background-image:url('images/header-bg.png');
}

#menu {
    width:100%;
    height:40px;
    background-color:#F4F4F4;
    clear: both;
    margin: 0 auto;
    text-align:center;
}


#content {
    width:700px;
    height:auto;
    float:left;
    background-color:blue;

}

#sidebar {
    width:300px;
    height:auto;
    float:left;
    background-color:gray;

}

#footer {
    clear: both;
    width:100%;
    height:90px;
    position:absolute;
    bottom: 0;
    margin: 0 auto;
    background-image:url('images/footer-bg.png');
}

.header {
    width:1000px;
    height:auto;
    margin-left:auto;
    margin-right:auto;
    color:#FFFFFF;
    font-size:14px;
    padding:15px;
}

.curly-font {
    font-family:'Pacifico', Verdana;
    font-size:30px;
    color:#FFFFFF;
}

.menu {
    width:1000px;
    height:auto;
    margin-left:auto;
    margin-right:auto;
    text-align:left;
}

3 个答案:

答案 0 :(得分:2)

将它们包裹在另一个div中,相对定位并添加margin: 0 auto;。容易做到;)

(下面的片段中的宽度只是为了显示效果)

&#13;
&#13;
#content {
  width:70px;
  height:50px;
  float:left;
  background-color:blue;

}

#sidebar {
  width:30px;
  height:50px;
  float:left;
  background-color:grey;

}
#wrapper {
  width: 100px;
  position: relative;
  margin: 0 auto;
}
&#13;
<div id="wrapper">
  <div id="content">
  </div>
  <div id="sidebar">
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您的意思是将宽度为1000像素的div居中,那么您可以使用margin:0 auto;

示例:

 <div id="container">   
    <div id="content">Main content</div>
    <div id="sidebar">Sidebar/Widget</div>
 </div>

css:

#container {width:1000px; margin: 0 auto;}

正在使用 DEMO

答案 2 :(得分:0)

这样做:

HTML

    <div id="wrapper">

    <div id="content">Main content</div>

    <div id="sidebar">Sidebar/Widget</div>

    </div>

CSS

    #wrapper {
        width: 1000px;
        margin: 0 auto;
    }

    #content {
        width:700px;
        height:auto;
        float:left;
        background-color:blue;

    }

    #sidebar {
        width:300px;
        height:auto;
        float:left;
        background-color:gray;

    }