How to Create Dropdown Menu in HTML: Simple Guide
To create a dropdown menu in HTML, use the
<select> tag to define the menu and <option> tags inside it for each choice. This creates a list users can click to pick one option.Syntax
The dropdown menu uses the <select> tag as a container. Inside it, each <option> tag represents a choice the user can select. You can add attributes like name to identify the menu and value to specify the data sent when a choice is selected.
html
<select name="menu"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select>
Output
A dropdown menu showing 'Option 1', 'Option 2', and 'Option 3' as choices.
Example
This example shows a simple dropdown menu with three options. When you click the menu, you see the list and can pick one.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dropdown Menu Example</title> </head> <body> <label for="fruits">Choose a fruit:</label> <select id="fruits" name="fruits"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="cherry">Cherry</option> </select> </body> </html>
Output
A labeled dropdown menu with options: Apple, Banana, Cherry.
Common Pitfalls
Common mistakes include forgetting the name attribute, which is needed to identify the dropdown in forms. Another is not using the label tag for accessibility, making it harder for screen readers. Also, avoid placing interactive elements inside <option> tags because they only accept text.
html
<!-- Wrong: Missing name attribute and label --> <select> <option>Red</option> <option>Green</option> </select> <!-- Right: Includes name and label for accessibility --> <label for="colors">Pick a color:</label> <select id="colors" name="colors"> <option value="red">Red</option> <option value="green">Green</option> </select>
Output
First dropdown without label and name; second dropdown with label and name for better accessibility.
Quick Reference
- <select>: Container for dropdown options.
- <option>: Each choice inside the dropdown.
- name: Attribute to identify the dropdown in forms.
- value: Data sent when an option is selected.
- label: Connects text label to dropdown for accessibility.
Key Takeaways
Use
Always include a
Each
Dropdown menus only accept text inside
Test your dropdown in a browser to ensure it displays and works correctly.