CSS下拉菜单奇怪的行为

时间:2014-10-19 01:30:44

标签: css

我正在尝试创建一个纯CSS菜单,但我不确定我做错了什么。问题是,当我将鼠标悬停在父元素上时,子列表会在“内部”打开,哪种打开另一个框并将所有其他父母推下。我知道单词不会使情景公正,所以如果有人可以试一试并告诉我错误,我将不胜感激:

<ul class="navigation">
  <li><a href="#">Employees</a>
    <ul>
      <li><a href="#">Add new</a></li>
      <li><a href="#">Edit details</a></li>
    </ul>
  </li>
  <li><a href="#">Attendance</a>
    <ul>
      <li><a href="#">View report</a></li>
      <li><a href="#">Upload attendance</a></li>
    </ul>
  </li>
  <li><a href="#">Broadcast</a>
      <ul>
      <li><a href="#">To all</a></li>
      <li><a href="#">To Managers</a></li>
    </ul>
  </li>
  <li><a href="#">Log out</a></li>
</ul>

CSS:

/* Begin styling navigation */

.navigation {
    text-align: center;
    margin: 20px auto;
}

.navigation li a {
    color: white;
    text-decoration: none;
}

.navigation li {
    list-style-type: none;
    background-color: #ff6600;
    padding: 5px;
}

.navigation ul {
    display: none;
}

.navigation > li {
    display: inline-block;
}

.navigation li:hover {
        background-color: #aaa;
}

.navigation li:hover > ul {
    display: block;
}

/* End styling navigation */

1 个答案:

答案 0 :(得分:2)

您需要将position: absolute添加到.navigation li:hover > ul的CSS中,如下所示:

.navigation li:hover > ul {
    display: block;
    position: absolute;
}

&#13;
&#13;
.navigation {
    text-align: center;
    margin: 20px auto;
}

.navigation li a {
    color: white;
    text-decoration: none;
}

.navigation li {
    list-style-type: none;
    background-color: #ff6600;
    padding: 5px;
}

.navigation ul {
    display: none;
}

.navigation > li {
    display: inline-block;
}

.navigation li:hover {
        background-color: #aaa;
}

.navigation li:hover > ul {
    display: block;
    position: absolute;
    padding-left: 0px;
}
&#13;
<ul class="navigation">
  <li><a href="#">Employees</a>
    <ul>
      <li><a href="#">Add new</a></li>
      <li><a href="#">Edit details</a></li>
    </ul>
  </li>
  <li><a href="#">Attendance</a>
    <ul>
      <li><a href="#">View report</a></li>
      <li><a href="#">Upload attendance</a></li>
    </ul>
  </li>
  <li><a href="#">Broadcast</a>
      <ul>
      <li><a href="#">To all</a></li>
      <li><a href="#">To Managers</a></li>
    </ul>
  </li>
  <li><a href="#">Log out</a></li>
</ul>
&#13;
&#13;
&#13;