LogRocket Blog

Creating a custom <select> dropdown with CSS

thumbnail

Creating a Custom Dropdown with CSS

Understanding how the element works

  • The <select> element is commonly used in forms to collect user input.
  • Achieving consistent styling for the native element across different browsers is challenging.
  • The native dropdown is implemented as a web component inside a shadow DOM.
  • The shadow DOM prevents conflicts between the styles of the component and other elements in the DOM.

Customizing the dropdown with CSS only

  • By using CSS, we can achieve consistent styling for the native dropdown.
  • CSS pseudo-elements can be used to create a custom arrow without adding additional HTML.
  • Disallowing pointer events on the arrow ensures the dropdown opens as expected when interacting with the arrow.

Adding a custom arrow to the native dropdown

  • By using CSS pseudo-elements, we can create a custom arrow.
  • Styling the native dropdown to resemble the browser's default appearance ensures a consistent design across browsers.
  • The dropdown maintains a familiar and uniform look for users.

Considerations for a CSS-only implementation

  • Custom styles are limited to the initial appearance of the dropdown.
  • Once the dropdown is opened, the list of options will have the browser's default styling.

Creating a custom dropdown from scratch with CSS and JavaScript

  • Manually assemble the necessary elements to create a custom dropdown.
  • Use radio buttons in the dropdown for smooth keyboard navigation.
  • The dropdown will have the same appearance across different browsers.

Adding accessibility features

  • Add appropriate ARIA attributes to make the dropdown more accessible for people with disabilities.
  • Ensure keyboard navigation and screen readers work properly with the custom dropdown.