How to horizontally center two divs within a header div?

那年仲夏 提交于 2019-12-06 03:52:23

A method that works with changing widths of the header and/ or of the two divs (if the title gets longer or shorter or if navigation items are added or removed):

Set text-align: center on the #header, and display: inline-block on #title and #navigation - demo http://dabblet.com/gist/3151355

Changes in CSS:

#header {
    position:fixed;
    top:0;
    left:0;
    right:0;
    background-color:#333333;
    padding:20px;
    text-align: center; /* added */
}
#title {
    color:#000000;
    font-size:30px;
    margin-right:24px;
    display: inline-block; /* took out float:left and added this */
    background-color:#ffffff;
    padding:8px;
}
#navigation {
    display: inline-block; /* added */
}

I've also added #navigation ul li:last-child {margin-right:0} in order not to have 24px margin after the last list item (which would make it seem like there is more space on the right side of the navigation)

You can wrap the title and navigation divs in another div, and then center that div using margin: 0 auto.

HTML

<div id="header">
    <div id="center">
        <div id="title">Some Title Text</div>
        <div id="navigation">
            <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
            </ul>
        </div>
    </div>
</div>​​​​​​​​

CSS

#center {
    width: 500px; /* or any other width */
    margin: 0 auto;
}

JS Fiddle: http://jsfiddle.net/rJyuJ/

hi could you please try with following css for #header

#header {
    position:fixed;
    top:0;
    left:0;
    right:0;
    background-color:#333333;
    padding:20px;
    text-align:center;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!