如何使用 CSS 创建分割按钮下拉菜单?
在网页的菜单部分,您一定见过下拉菜单。当鼠标光标停留在下拉菜单按钮上时,子菜单就会显示出来。这种分割按钮看起来像是同一按钮内的不同部分。这可以通过箭头键或底部箭头来表示。让我们看看如何使用 HTML 和 CSS 创建这样的菜单。
创建下拉菜单按钮
使用 <button> 元素为下拉菜单创建一个按钮 -
<button>Button</button>
像这样设置按钮的样式 -
button {
background-color: rgb(18, 5, 95);
color: white;
padding: 16px;
font-size: 20px;
font-weight: bolder;
font-family: monospace, sans-serif;
border: none;
outline: none;
}
创建分割按钮
使用箭头键来表示带有菜单链接的下拉菜单。我们设置了一个 div 容器 -
<div class="dropMenu">
<button>>></button>
<div class="dropContent">
<a href="#">First Link</a>
<a href="#">Second Link</a>
<a href="#">Third Link</a>
</div>
</div>
定位下拉菜单
使用 position 属性和 absolute 值来定位下拉菜单。菜单的 display 属性设置为 inline-block -
.dropMenu {
position: absolute;
display: inline-block;
}
.dropMenu button {
border-left: 1px solid #0d8bf2;
}
定位下拉内容
下拉菜单中的链接(即菜单链接)设置为绝对定位。默认情况下,下拉内容(即菜单链接)是不可见的,即 display 属性设置为 none。只有当鼠标光标放置在上面时才会显示。-
.dropContent {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
z-index: 1;
}
.dropContent a {
color: black;
background-color: rgb(184, 253, 255);
font-size: 18px;
font-weight: bold;
padding: 12px 16px;
text-decoration: none;
display: block;
}
悬停时显示下拉菜单
当鼠标悬停时,下拉菜单链接会显示出来。为此,使用了 :hover 选择器 -
.dropContent a:hover {
background-color: rgb(48, 0, 110);
color: white;
}
.dropMenu:hover .dropContent {
display: block;
}
示例
以下是使用 CSS 创建分割按钮下拉菜单的代码 -
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Lucida Sans", "Lucida Sans Regular", "Lucida Grande", "Lucida Sans Unicode", Geneva, Verdana, sans-serif;
}
button {
background-color: rgb(18, 5, 95);
color: white;
padding: 16px;
font-size: 20px;
font-weight: bolder;
font-family: monospace, sans-serif;
border: none;
outline: none;
}
.dropMenu {
position: absolute;
display: inline-block;
}
.dropMenu button {
border-left: 1px solid #0d8bf2;
}
.dropContent {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
z-index: 1;
}
.dropContent a {
color: black;
background-color: rgb(184, 253, 255);
font-size: 18px;
font-weight: bold;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropContent a:hover {
background-color: rgb(48, 0, 110);
color: white;
}
.dropMenu:hover .dropContent {
display: block;
}
.btn:hover,
.dropMenu:hover .btn {
background-color: #0b7dda;
}
</style>
</head>
<body>
<h1>Split Button dropMenu Example</h1>
<button>Button</button>
<div class="dropMenu">
<button>
>>
</button>
<div class="dropContent">
<a href="#">First Link</a>
<a href="#">Second Link</a>
<a href="#">Third Link</a>
</div>
</div>
<h1>Hover over '>>' to open dropMenu menu</h1>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP