当前位置: 动力学知识库 > 问答 > 编程问答 >

navbar - CSS navigation bar - centering based on element within nav bar

问题描述:

I'm trying to create a nav bar with four elements, two smaller buttons that will link to the homepage and a contact page, and then two larger buttons that will link to the two main sections of the site. I'm trying to position things in such a way that the two large buttons are centered, with the two smaller buttons to the left of them.

I can't "margin: 0 auto;" the two large buttons inside their own div as I would have to set it to "display: block;" which sets them on a different line than the smaller buttons, and absolutely positioning things messes up the layout as soon as the browser window changes.

I feel like I'm missing something simple here. Am I going at this from the wrong angle?

Here's a Dabblet of what I have at the moment... http://dabblet.com/gist/6287837

HTML

<div id="nav-container">

<div id="small-button-container">

<img src="http://placehold.it/47x22" class="small-button01" />

<img src="http://placehold.it/70x42" class="small-button02" />

</div>

<div id="big-button-container">

<img src="http://placehold.it/360x64" />

<img src="http://placehold.it/360x64" />

</div>

</div>

CSS

#nav-container{

outline: 1px red dashed;

width: 1000px;

display: block;

margin: 0 auto;}

#small-button-container{

display: inline-block;

width: 136px;

position: relative;

top: -22px;

left: 40px;}

#big-button-container{

display: inline-block;

width: 780px;

height: 64px;

margin-left: 70px;}

.small-button01{

display: inline;

position: relative;

left: 5px;}

.small-button02{

display: inline;

position: relative;

left: 15px;}

网友答案:

You can apply position: absolute; to your #small-button-container, so the the big buttons will centre.

Note we put position: relative; on the parent container so the #small-button-container will be positioned absolutely relative to it's parent.

CSS

#nav-container {
    outline: 1px red dashed;
    width: 1000px;
    display: block;
    margin: 0 auto;
    text-align: center;
    position: relative;
}
#small-button-container {
    position: absolute;
    top: 0;
    left: 0;
}

Demo

网友答案:

In addition to position: absolute you can also try using a negative left margin on #nav-container if you know the computed width of #small-button-container. You can use text-align: center on #nav-container. Since it's a div you don't need to use display:block too. If you have additional padding on #small-button-container you'll need to take this into account.

#nav-container {
   margin: 0px auto;
   text-align: center;
   margin-left: -136px;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: