如何创建:可悬停的下拉菜单

学习如何使用 CSS 创建可悬停的下拉菜单。

下拉菜单

下拉菜单是一种可切换的菜单,允许用户从预定义列表中选择一个值:

Try it yourself

创建可悬停的下拉菜单

创建一个下拉菜单,当用户将鼠标移动到元素上时显示该菜单。

第一步 - 添加 HTML:

<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

Example explanation:

使用任何元素打开下拉菜单,例如 <button>、<a> 或 <p> 元素。

使用容器元素(如 <div>)创建下拉菜单,并在其中添加下拉菜单链接。

使用 <div> 元素将按钮和 <div> 包装起来,以便使用 CSS 正确定位下拉菜单。

第二步 - 添加 CSS:

/* 下拉按钮 */
.dropbtn {
  background-color: #04AA6D;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
}
/* 容器<div> - 用于定位下拉菜单内容 */
.dropdown {
  position: relative;
  display: inline-block;
}
/* Dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}
/* Links within the dropdown menu */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
/* Change the color of the dropdown menu link when the mouse hovers over it */
.dropdown-content a:hover {background-color: #ddd;}
/* Display the dropdown menu when the mouse hovers over it */
.dropdown:hover .dropdown-content {display: block;}
/* Change the background color of the dropdown button when displaying the dropdown content */
.dropdown:hover .dropbtn {background-color: #3e8e41;}

Try it yourself

Example explanation:

We have set the style for the dropdown menu button with background color, padding, etc.

.dropdown class is used position:relativewhen we want to place the dropdown menu content directly below the dropdown menu button (using position:absolute), which is necessary.

.dropdown-content The class contains the actual dropdown menu. It is hidden by default and will be displayed when the mouse hovers over it (see below). Note that the minimum width is set to 160px. Feel free to change this setting. Tip: If you want the width of the dropdown menu content to be the same as the dropdown menu button, set the width to 100% (and set overflow:auto to enable scrolling on small screens).

We did not use borders but used box-shadow Property to make the dropdown menu look like a 'card'. We also use z-index Place the dropdown menu in front of other elements.

:hover The selector is used to display the dropdown menu when the user moves the mouse over the dropdown menu button.

Right-aligned dropdown list

Try it yourself

Dropdown list in the navigation bar

Try it yourself

Relevant pages

Tutorial:CSS dropdown menu

Tutorial:How to create a clickable dropdown menu