8

我正在尝试创建纯粹而简单的 CSS 下拉菜单,它将在每个项目下方以全宽模式打开,但也会将每个下拉菜单保留在其父项目下方。这张图片更好地解释了我想要实现的目标:

在此处输入图像描述

我只是不知道如何将嵌套的 UL 保留在每个 li 内,但也有一个全宽的背景将它包裹起来。

这是我在Codepan上准备的演示:http: //cdpn.io/wLjFm

4

1 回答 1

12

/* not very relevant styling */
h1         { font-size: 20px; padding-top: 20px; }
.container { position: relative; margin: 20px auto 0 auto; width: 75%; }
.header    { background: #eee; }
.nav       { background: #ccc; }

/* relevant styling */
body { overflow-x: hidden; } /* trick from css-tricks comments */

/* FIRST LEVEL */

.nav > ul > li { 
  display: inline-block; 
  position: relative; 
  padding: 3px 10px 3px 0;
  z-index: 100;
}

/* SECOND LEVEL */
.nav > ul > li > ul {
  position: absolute;
  left: 0;
  top: 100%;
  padding: 0 1000em; /* trick from css-tricks comments */
  margin: 0 -1000em; /* trick from css-tricks comments */
  z-index: 101;
  visibility: hidden;
  opacity: 0;
  background: rgba(255, 240, 240, 0.8);
}

.nav > ul > li:hover > ul {
  visibility: visible;
  opacity: 1;
}

.nav > ul > li > ul > li {
  padding: 3px 0;
}

.nav > ul > li:hover .drop {
  font-weight: bold;
}
<div class="header">

  <div class="container">
    <h1>Hank's Big Leauge Widgets</h1>
    <span>You want a widget? we got 'em!</span>
  </div>


  <!-- NAVIGATION -->    
  <div class="nav">
    <ul class="container">
      <li>
        <a class="drop" href="#">Products</a>
        <ul>
          <li><a href="#">Widget A</a></li>
          <li><a href="#">Widget B</a></li>
          <li><a href="#">Widget C</a></li>
        </ul>
      </li>
      <li>
        <a class="drop" href="#">Locations</a>
        <ul>
          <li><a href="#">Location A</a></li>
          <li><a href="#">Location B</a></li>
          <li><a href="#">Location C</a></li>
        </ul>
      </li>
      <li>
        <a class="drop" href="#">Staff</a>
        <ul>
          <li><a href="#">President</a></li>
          <li><a href="#">VP</a></li>
          <li><a href="#">Manager</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>

<div class="content container">
  <p>All sorts of content</p>
  <p>All sorts of content</p>
  <p>All sorts of content</p>
  <p>All sorts of content</p>
  <p>All sorts of content</p>
  <p>All sorts of content</p>
</div>


**CSS and HTML**

演示

JSFIDDLE

于 2013-06-23T14:12:47.640 回答