如何使用定位和 CSS 在下拉菜单上显示子菜单? [英] How to display submenu on dropdown using positioning and CSS?

查看:29
本文介绍了如何使用定位和 CSS 在下拉菜单上显示子菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设计有这个简单的导航菜单.但问题是我无法在悬停时显示子菜单.有没有办法解决这个问题?还是我的 CSS 缺少一些样式?

I have this simple navigation menu for my design. But the problem is I can't display the sub menu when hovered. Is there any way to solve this? Or does my CSS has some missing styles?

nav ul {list-style-type: none; overflow: hidden; background: #000; position: relative;}
nav li {float: left;}
nav li > a {padding: 15px 15px; display: inline-block; text-decoration: none; color: white; text-align: center;}
nav li > a:hover {background: violet;}

nav ul ul { position: absolute; background: green; top: 100%;}
nav ul ul li > a:hover {color: red;}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>sample UL</title>
    <style media="screen">

    </style>
  </head>
  <body>
    <nav>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Menu 1</a></li>
        <ul>
          <li><a href="#">submenu 1</a></li>
          <li><a href="#">submenu 2</a></li>
        </ul>
      </ul>
    </nav>
  </body>
</html>

推荐答案

您的代码中有不少错误.最关键的是子菜单容器上的top:100%,将其移出可见区域.

There are quite a few errors in your code. The most critical one is the top: 100% on the submenu container, which moves it out of the visible area.

除此之外,将子菜单标题li 定义为position:relative 和子菜单ul 本身默认为display: none 和悬停 display: block.并将子菜单容器放入作为其标题的li.请参阅下面的代码:

Apart from that it's important to define the submenu header li as position: relative and the submenu ul itself by default display: none and on hover display: block. And put the submenu container into the li that serves as its header. See my code below:

nav ul {
  list-style-type: none;
  background: #000;
}

nav li {
  display: inline-block;
  position: relative;
}

nav li>a {
  padding: 15px 15px;
  display: inline-block;
  text-decoration: none;
  color: white;
  text-align: center;
}

nav li>a:hover {
  background: violet;
}
nav ul li ul {
  display: none;
  position: absolute;
  top: 45px;
  left: 0px;
  width: 100px;
  overflow: visible;
  padding: 0;
}
nav ul li:hover ul {
  display: block;
}
nav ul ul li {
  background: green;
  display: block;
}
nav ul ul li>a:hover {
  color: red;
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>sample UL</title>
  <style media="screen">

  </style>
</head>

<body>
  <nav>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Menu 1</a>
        <ul>
          <li><a href="#">submenu 1</a></li>
          <li><a href="#">submenu 2</a></li>
        </ul>
      </li>
    </ul>
  </nav>
</body>

</html>

这篇关于如何使用定位和 CSS 在下拉菜单上显示子菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆