纯CSS粘性水平Subnav-下拉列表不显示

时间:2018-10-23 04:11:33

标签: html css drop-down-menu sticky

我正在尝试在CSS中创建水平子导航栏(没有无序列表),但是无法显示下拉菜单。 这是我的HTML代码:

<div class="navbar sticky">
  <a href="#e">Home</a>
  <div class="subnav">
    <button class="subnavbtn">Learn <i class="fa fa-caret-down"></i></button>
    <div class="subnav-content">
      <a href="#">Print</a>
      <a href="#">Review</a>
      <a href="#">Examples</a>
      <a href="#">More Info</a>
    </div>
  </div>
  <div class="subnav">
    <button class="subnavbtn">Game <i class="fa fa-caret-down"></i></button>
    <div class="subnav-content">
      <a href="#">Play Now!</a>
      <a href="#">How to Play</a>
      <a href="#">Cards</a>
    </div>
  </div>
  <a href="#">Minigames</a>
</div>

这是我在CSS中的代码:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.navbar {
  overflow: hidden;
  background-color: green;
  position: sticky;
  top: 0;
}

.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.subnav {
  float: left;
  overflow: hidden;
}

.subnav .subnavbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.navbar a:hover,
.subnav:hover .subnavbtn {
  background-color: chartreuse;
  color: black;
}

.subnav-content {
  display: none;
  position: absolute;
  left: 0;
  background-color: red;
  width: 100%;
  z-index: 1;
  visibility: hidden;
}

.subnav-content a {
  float: left;
  color: white;
  text-decoration: none;
  display: inline;
}

.subnav-content a:hover {
  background-color: #eee;
  color: black;
}

.subnav:hover .subnav-content {
  visibility: visible;
  display: block;
}

我尝试过更改不透明度,甚至使用可见性,但对我来说不起作用。有时会出现下拉菜单,但是顶部导航栏将发生变化(“游戏”链接将向右移动,即使它们位于不同的栏中,也将从“更多信息”结束的点开始)。 在搜索此问题时,我看到的大多数解决方案是它们没有使用(display:block;),但是我一直在使用,我不知道此时该怎么做。

这里是fiddle

3 个答案:

答案 0 :(得分:1)

只需从类名为position的{​​{1}}中删除div属性。

navbar

答案 1 :(得分:1)

从您的overflow:hidden;声明中删除.navbar并将其替换为float:left;width:100%;

Floated elements从父元素的计算高度中删除。但是,overflow:hidden;调用了要通过block formatting context计算的高度,但是隐藏了下拉菜单,这是因为溢出被​​隐藏了。

此外,浮动父元素意味着子元素决定了父元素的高度,使其更具动态感。

Revised Fiddle Here

答案 2 :(得分:0)

下拉菜单显示在导航栏的外面。 因此,您应将overflow: hidden中的height: 50px替换为.navbar

.navbar {
  height: 50px;
  background-color: green;
  position: sticky;
  top: 0;
}