簡體   English   中英

如何將兩個div並排居中?

[英]How do I center two divs that are side by side?

我想將Div的#Content和#Sidebar居中放置,這是我的代碼,如果Div並排,有人可以解釋一下我該怎么做嗎?

我已經更新了現有帖子以提供更多信息-謝謝!

<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;
}

將它們包裝在另一個div中,相對放置並添加margin: 0 auto; 輕而易舉 ;)

(以下代碼段中的寬度只是為了可視化效果)

 #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; } 
 <div id="wrapper"> <div id="content"> </div> <div id="sidebar"> </div> </div> 

如果您打算將寬度為1000px的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;}

工作演示

像這樣做:

的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;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM