【问题标题】:CSS drop down menu is not working as expectedCSS 下拉菜单未按预期工作
【发布时间】:2014-02-04 10:52:25
【问题描述】:

当我将 div(包含下拉菜单)定位为相对且下拉菜单 div 的定位为绝对时,它只显示下拉菜单上的最后一项。如果我设置下拉菜单容器 div相对并保留下拉菜单 div 定位,然后它可以工作。但这会影响页面的其余部分。因此,如何设置使下拉菜单工作而不影响页面任何其他部分的定位。

HTML

  <div id="top_head">
  My Online Shop
    <div id="nav">
      <div class="test"><a href="home.php">Home</a></div>
      <div class="test" id="product"><a href="produt.php">Products</a>
           <div class="test1"><a href="about.php">shirt</a></div>
           <div class="test1"><a href="about.php">Pant</a></div>
           <div class="test1"><a href="about.php">inner</a></div>
           <div class="test1"><a href="about.php">cap</a></div>
      </div>
      <div class="test"><a href="about.php">About</a></div>
      <div class="test"><a href="contact.php">contact Us</a></div>
    </div>
   </div>

CSS

body{
   color:green;
}
#top_head{
   width:100%;
   height:100px;
   font:48px Arial green;
   border:1px dotted red;

}
#nav{
   background-color:gray;
   width:57%;
   border-radius:5px;
   font:28px Arial orange;
   margin:0px -49px 5px 15px;
}
#nav a{
   color:red;
   text-decoration:none;
   margin:0px 50px;
}
.test{
   float:left;
}
.test:hover{
   background-color:orange;
}
#product{
   position:relative;
}
.test1{
   position:absolute;
   border:1px solid red;
   visibility:hidden;
}
   #product:hover .test1{
   visibility:visible;
   background-color:yellow;
}

我也尝试过使用显示属性。结果相同。 如果您知道问题出在哪里,请提供帮助。

【问题讨论】:

  • 你为什么不使用uls 和lis?为什么不使用one of the many that have been made already?
  • 请整理一个 jsfiddle 以帮助更好地了解问题。
  • “它只向我显示下拉菜单上的最后一项” – 当然会发生这种情况,因为您绝对定位了 @ 的 all 987654326@ 元素,但没有为每个元素指定不同的 top 值——所以它们最终都在彼此之上。如果您要按照@ZachSaucier 建议的那样使用列表以明智的方式实现这一点,那么您就不会遇到这个问题,因为您只需定位包含所有子菜单项的列表,这样物品本身就可以正常流动,不会相互重叠。
  • 是的,这个话题已经被网络上所有史诗般的广度所覆盖,所以请做一些适当的研究并采用众多现有解决方案中的一种。毕竟 SO 不是教你 CSS basics 的地方。

标签: css html css-position


【解决方案1】:

看起来这里的问题是您在所有子菜单 div 上都使用了position:absolute。这实质上是使它们彼此叠放(将最后一个放在顶部)。

对此的一种解决方案是将所有这些元素包装在一个容器 div 中,并使其成为隐藏或显示的东西:

Working Fiddle Demo

您的子菜单变为:

 <div class="test1">
   <div><a href="about.php">shirt</a></div>
   <div><a href="about.php">Pant</a></div>
   <div><a href="about.php">inner</a></div>
   <div><a href="about.php">cap</a></div>
 </div>

CSS 略有改动:

.test1{
  display:none;
}

.test1 div{
   border:1px solid red;
}

#product:hover .test1{
 position:absolute;
 display: block;
 background-color:yellow;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2018-07-04
    相关资源
    最近更新 更多