liveBook · Manning

Dropdown

As explained in CSS in Depth, Second Edition

A dropdown is an interface control that reveals a list or panel of selectable options when activated.

A dropdown keeps a toggle visible and reveals a menu of selectable links when activated. Positioning the menu outside the page flow lets it appear over nearby content without shifting the layout. section 6.3.1

A common construction places the dropdown container relatively and the hidden menu absolutely, aligned beneath the toggle. A click handler toggles an open class, which CSS uses to display the menu. Prefer click activation to a hover-only approach when keyboard or touchscreen use matters. section 6.3.1

Transitions can make a menu open smoothly rather than snap into view. Fading with opacity and animating height are two approaches, each with its own complications. section 15.3

Listing 6.9 Displaying the open dropdown menu
.dropdown {
  display: inline-block;
  position: relative;         #1
}

.dropdown-toggle {
  padding: 0.5em 1.5em;
  border: 1px solid #ccc;
  background-color: #eee;
  border-radius: 0;
}

.dropdown-menu {
  display: none;          #2
  position: absolute;
  left: 0;
  top: 2.1em;                  #3
  inline-size: max-content;
  min-inline-size: 100%;
  background-color: #eee;
}

.dropdown.is-open .dropdown-menu {   #4
  display: block;                    #4
}                                    #4

.submenu {
  padding-inline-start: 0;
  margin: 0;
  list-style-type: none;
  border: 1px solid #999;
}

.submenu > li + li {
  border-top: 1px solid #999;
}

.submenu > li > a {
  display: block;
  padding: 0.5em 1.5em;
  background-color: #eee;
  color: #369;
  text-decoration: none;
}

.submenu > li > a:hover {
  background-color: #fff;
}

See the CSS pattern for positioning the menu and showing it when the dropdown has its open class. section 6.3.1

How CSS in Depth, Second Edition covers it

How deep it goes
Explains menu markup, click handling, positioning, and opacity or height transitions.
Examples
Builds a Main Menu with links, then uses a separate menu to demonstrate fade and height effects.
What you can do after
Build a click-operated menu by toggling an open class and positioning its panel outside normal flow.
How it connects
Connects relative and absolute positioning with JavaScript, hover behavior, and CSS transitions.

Also explained in

Compare how 10 books explain dropdown →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.