How to create a dropdown menu in Bootstrap ?
A dropdown menu offers a list of alternatives when clicked or hovered on, which is a clean method of providing a list of alternatives as only one option is displayed initially onto the screen. Drop-down menus are used in almost all types of software nowadays to show sub-options of the option.
Step 1: To include this drop-down into your website by making use of bootstrap, you just need to include the following jQuery and bootstrap js libraries, as scripts in your HTML code.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js”></script>
Step 2: Include the following stylesheet in the head of the HTML document to give an appearance of a dropdown.
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css”>
Step 3: And make sure to enclose the dropdown menu within the .dropdown class, the button or the main option within .btn btn-primary dropdown-toggle class, and the list of alternatives within the .dropdown-menu class as below.
<div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Data Structures <span class="caret"></span> </button> <ul> <li><a href="#">Array</a></li> <li><a href="#">Stack</a></li> <li><a href="#">Queue</a></li> </ul> </div>
The class .caret is used to display the little upside-down triangle in the button as shown in the output.
Example:
HTML
<!DOCTYPE html> < html > < head > < meta name = "viewport" content = "width=device-width, initial-scale=1" > < link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" > </ script > < script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" > </ script > < style > .container { color: green; } </ style > </ head > < body > < div class = "container" > < h1 >w3wiki</ h1 > < h2 >Dropdowns</ h2 > < div class = "dropdown" > < button class = "btn btn-primary dropdown-toggle" type = "button" data-toggle = "dropdown" > Data Structures < span class = "caret" ></ span > </ button > < ul class = "dropdown-menu" > < li >< a href = "#" >Array</ a ></ li > < li >< a href = "#" >String</ a ></ li > < li >< a href = "#" >Stack</ a ></ li > < li >< a href = "#" >Queue</ a ></ li > < li >< a href = "#" >Map</ a ></ li > < li >< a href = "#" >Tree</ a ></ li > </ ul > </ div > </ div > </ body > </ html > |
Output: As you can see in the output, the dropdown button is created with the name Data Structures, and on clicking it, you are provided with a list of options as you can see above.
Contact Us