CSS中心和侧面Div子菜单

时间:2014-05-10 10:59:52

标签: html css

HTML:

<div id="nav">
  <ul id="main-nav">
    <li> <a href="#">Home</a> </li>
    <li>
      <a href="#">Catagory</a>
      <ul class="sub-nav">
        <li> <a href="#">SubCat1</a> </li>
        <li>
          <a href="#">SubCat2</a>
          <ul>
            <li> <a href="#">SubCat2Sub</a> </li>
            <li> <a href="#">SubCatSsub</a> </li>
          </ul>
        </li>
      </ul>
    </li>
    <li> <a href="#">About</a> </li>
    <li> <a href="#">How to order</a> </li>
  </ul>
</div>

如何将div id="nav"居中?如何在Subcat1旁边制作Subcat2?

请参阅JSFiddle了解演示。

3 个答案:

答案 0 :(得分:1)

使用以下CSS(评论更改)

#nav{
    font-size: 1px;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
 }

 #nav ul{
    padding: 0;
    list-style: none;
 }

 #nav a{
    background: pink;
    color: yellow;
    font-family: sans-serif;
    text-decoration: none;
 }

 #nav a:hover{
    background: pink;
 }

 #main-nav{
 }

 #main-nav > li{
    float: left;
 }

 #main-nav > li > a{
    font-size: 18em;
    line-height: 2em;
 }

 .sub-nav > li{
    display: inline-block; /* brings elements beside each other */
    vertical-align: top; /* makes elements more towards top of their parent */
 }

 .sub-nav > li > a{
    font-size: 16em;
    line-height: 1.5em;
    background: blue;
 }

 .sub-nav ul{
    top: 0;
 }

 .sub-nav ul a{
    font-size: 14em;
    line-height: 1.5em;
    background: red;
 }

 #main-nav li:hover > ul{
    display: block;
    text-align: left;
 }

 .sub-nav, .sub-nav ul{
    display: none;
    position: absolute;
 }

 #main-nav li:hover > ul li ul{
    display: block;
    position: relative;
 }

 #main-nav{display: inline-block;} /*it makes parent's text-align: center; take effect on it*/

答案 1 :(得分:0)

如果您有#nav的父元素(或者您可以使用body),则可以将父级设置为text-align:center,将#nav设置为display:inline-block

<强> JSFiddle Demo

<强> CSS

body {
    text-align: center;
}

#nav {
    font-size: 1px;
    text-align:center; 
    margin-left:auto; 
    margin-right:auto; 
    display: inline-block;

}

答案 2 :(得分:-1)

也许你可以用它来解决你的问题

http://jsfiddle.net/7g7c6/

#nav {
    font-size: 1px;
    text-align:center; 
    margin:0 auto;
    width:100%;
    margin-left:250px;
}