如何使用純CSS創建下拉菜單
使用HTML和CSS可創建無需JavaScript的下拉菜單。 2. 通過:hover偽類觸發子菜單顯示。 3. 利用嵌套列表構建結構,CSS設置隱藏與懸浮顯示效果。 4. 可添加過渡動畫提升視覺體驗。
A dropdown menu can be created using only HTML and CSS—no JavaScript required. The key is using the :hover pseudo-class to show a hidden submenu when a user hovers over a parent menu item. Below is a step-by-step guide to build a simple, functional dropdown menu.
1. HTML Structure
Start with a basic unordered list for your navigation. Use nested lists for the dropdown items.
2. Basic CSS Styling
Style the main menu as a horizontal bar. Hide the submenu by default, then display it on hover.
.menu {list-style: none;
padding: 0;
margin: 0;
background: #333;
}
.menu > li {
display: inline-block;
position: relative;
}
.menu a {
display: block;
padding: 15px 20px;
color: white;
text-decoration: none;
}
.menu a:hover {
background: #555;
}
3. Show Dropdown on Hover
Use CSS to hide the submenu initially and reveal it when the parent is hovered.
.submenu {list-style: none;
padding: 0;
margin: 0;
position: absolute;
top: 100%;
left: 0;
background: #444;
display: none;
min-width: 180px;
}
.dropdown:hover .submenu {
display: block;
}
.submenu li {
display: block;
}
.submenu a {
padding: 10px 15px;
}
.submenu a:hover {
background: #666;
}
4. Optional: Add Smooth Appearance
Improve the look with transitions and subtle effects.
.submenu {opacity: 0;
visibility: hidden;
transition: opacity 0.2s ease-in-out;
}
.dropdown:hover .submenu {
display: block;
opacity: 1;
visibility: visible;
}
With this approach, the dropdown appears smoothly on hover and disappears when the mouse moves away. It works across modern browsers and is accessible via keyboard navigation when structured properly.
Basically just combine clean HTML structure with smart use of :hover and positioning in CSS.
以上是如何使用純CSS創建下拉菜單的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策
