CSS TutorialLesson #93

CSS Dropdowns

CSS dropdowns are used to display a list of options or content when a user

CSS dropdowns are used to display a list of options or content when a user clicks or hover over an element, like a button or a navigation link.

A CSS dropdown consists of a trigger element (like <div>, <button>, <p>, <a>, etc.).

When the trigger element is clicked or hovered over, the dropdown content will be displayed.

The dropdown content is a container element (e.g. <div>) that holds the hidden content (can be text, links, images, etc.).

Mouse over the three CSS dropdown examples below:

Dropdown Text

Hello World!

<button class="dropbtn">Dropdown Menu</button>

Link 1) Link 2) Link 3)

Other: <img class="dropimg" src="img_5terre.jpg" alt="Cinque Terre" width="100" height="50">

<img src="img_5terre.jpg" alt="Cinque Terre" width="300" height="200"> Beautiful Cinque Terre


CSS Dropdown Box with Text

Here, we create a dropdown box with some text, that appears when the user mouses over a <div> element.

Example

Example Code

html
Try it Yourself
Live Output Preview:

Example Explained

  • The .dropdown class uses position:relative, which is needed when we want the dropdown content to be placed right below the trigger element (the dropdown content will use position:absolute).
  • The .dropdown-content class holds the dropdown content. It is hidden by default, and will be displayed on hover.
  • The min-width property is set to 130px. Feel free to change this! If you want the width of the dropdown content to be as wide as the trigger element, set width to 100% and overflow:auto to enable scroll on small screens.
  • Instead of using a border, we use the box-shadow property to make the dropdown content look like a "card".
  • The :hover selector is used to show the dropdown content when the user mouses over the element.

CSS Dropdown Menu

Create a dropdown menu that allows the user to choose an option from a list:

<button class="dropbtn dropbtn2">Dropdown Menu</button>

Link 1) Link 2) Link 3)

This example is similar to the previous one, except that we add a button and links inside the dropdown box and style them to fit the dropdown button:

Example

Example Code

html
Try it Yourself
Live Output Preview:


Interactive Code Examples

CSS Example 1

html
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview:

CSS Example 2

html
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview: