如何:居中水平菜单&子菜单

时间:2015-10-20 23:30:53

标签: javascript jquery html css

如何将此导航菜单和子菜单水平居中?设置较小的导航列表“宽度”并设置“边距:0自动”不起作用。我还想在页面的整个宽度上保持导航栏的背景颜色。

我的HTML:

<div class="slide-down-page">
    <ul id="nav">
    <li id= "bio"><a class="active btn" href="home.html">Bio</a></li>
    <li id= "portfolio"><a href="portfolio.html">Portfolio</a>
        <ul>
            <li><a href="#">Writing</a>
            </li>
            <li><a href="#">Illustrations</a></li>
            <li><a href="#">Design</a></li>
        </ul> 
    </li>
    <li id= "contact"><a href="contact.html">Contact</a></li>
    </ul>
</div>

我的CSS:

#nav{
margin: 0 ; padding: 0;
position: fixed;
width: 100%;
background:#e7e7e7;
}

#nav li {
list-style: none;
display: inline-block;
float: left;
}

#nav li a{
padding: 1em 2em;
display: inline-block;
text-decoration: none;
color: #F2583E;
font-family: 'Helvetica Neue';
font-size:1.25em;
background: #e7e7e7;
text-align: center;
margin: 0 auto;
}

#nav li a:hover{
background-color: #C1DAD6;
}

#nav a.active, #nav li:hover a.active{
background-color: #F2583E;
color: #F7F3E8;
cursor: default;
}

/*SubMenu*/
#nav li ul{
display: none;
}

#nav li:hover ul{
display: block;
position: absolute;
top: 63px;
width: 100%
left:0px;
background: #C1DAD6;
color:white;
}

#nav li:hover ul li, #nav li:hover ul li a{
display: inline-block;
float: left;
padding: 5px;
color:white;
background: #C1DAD6;
}

#nav li ul li:hover a{
color: #77bed2;
}

#nav li ul li{ 
 _display: inline-block; /* for IE5*/
 }

#nav li ul li a{
width: 150px;
}

1 个答案:

答案 0 :(得分:0)

如果你想用CSS做这个是方法:

1.删除&#34;浮动:左;&#34; &#34; #nav li&#34;和#34; #nav li:hover ul li,#nav li:hover ul li a&#34;

2.add&#34; text-align:center;&#34;到&#34;#nav&#34;

3.fix&#34;宽度:100%&#34; &#34; #nav li:hover ul&#34;添加&#34;;&#34;在&#34;宽度:100%&#34;

之后

4.add&#34;填充:0;&#34; to&#34; #nav li:hover ul&#34;

所以这是固定的CSS代码:

#nav{
margin: 0 ; padding: 0;
position: fixed;
width: 100%;
background:#e7e7e7;
text-align:center;
}

#nav li {
list-style: none;
display: inline-block;
}
#nav li a{
padding: 1em 2em;
display: inline-block;
text-decoration: none;
color: #F2583E;
font-family: 'Helvetica Neue';
font-size:1.25em;
background: #e7e7e7;
text-align: center;
margin: 0 auto;
}

#nav li a:hover{
background-color: #C1DAD6;
}

#nav a.active, #nav li:hover a.active{
background-color: #F2583E;
color: #F7F3E8;
cursor: default;
}

/*SubMenu*/
#nav li ul{
display: none;
}

#nav li:hover ul{
display: block;
position: absolute;
top: 63px;
width: 100%;
padding: 0;
left:0px;
background: #C1DAD6;
color:white;
}

#nav li:hover ul li, #nav li:hover ul li a{
display: inline-block;
padding: 5px;
color:white;
background: #C1DAD6;
}

#nav li ul li:hover a{
color: #77bed2;
}

#nav li ul li{ 
 _display: inline-block; /* for IE5*/
 }

#nav li ul li a{
width: 150px;
}