How To Create Custom Menus with CSS Select

adarshm1024

AdarshM1024

Posted on March 28, 2023

How To Create Custom Menus with CSS Select

When it comes to UI components, there are two versatile methods that we can use to build it for your website: either we can use prebuilt components from a well-known library or framework, or we can develop our UI components from scratch.

Developing unique CSS components is a better strategy because we have much more control over them as developers, and can change the values as and when required. As a front-end developer for more than three years, making custom select dropdown components for navigation, selecting an option from a list, or filtering the provided choice is one of the most common demands when building user interfaces.

There are several use cases for the < select > tag, like dropdowns, navigation menus, filtering lists of items based on the selected option, choosing an option from a given list of options in input forms, etc. There are numerous CSS frameworks and JavaScript libraries, including Bootstrap, Material UI, and Ant Design, and each of them has its own implementation of a custom CSS Select dropdown menu. They are extremely dependable and have demonstrated cross-browser functionality.

image

Source

Cross-browser drop-down styling is very challenging. Designers always create attractive drop-down lists, but each browser renders them slightly differently. You can learn more about browser rendering from this blog on Browser Engines: The Crux Of Cross Browser Compatibility.

When thinking about cross-browser functionality, using a CSS framework or library is beneficial because they handle all the behind-the-scenes tasks involved in creating a specific component.

When using these CSS libraries and frameworks like Bootstrap or Tailwind CSS, cross-browser functionality is paramount because end users use different operating systems, browsers, and devices. If we want everyone to have the same experience, we should only use those libraries and frameworks that work well on all devices, operating systems, and browsers. Most modern frameworks consider the need for cross browser compatibility and maintain device-friendly styling.

In this in-depth blog on custom CSS Select menus, we will walk through the process of creating various custom CSS Select menus.

So, let’s get started!

Emulators Online by LambdaTest allows you to seamlessly test your mobile applications, websites,and web apps on mobile browsers and mobile devices.

What is an HTML Select tag?

The HTML element < select > represents a control with a menu of choices. Usually, we use the select element to create a drop-down list. The < select > element is most frequently used in forms to gather user input.

Select tags use a variety of attributes, which give additional details about HTML elements. If we omit the name attribute, no data from the drop-down list will be submitted. The id attribute is needed to associate the drop-down list with a label. The < select > element define the options in the drop-down list.

<select>
  <option>
  </option>
  ...
</select>
Enter fullscreen mode Exit fullscreen mode

The < select > element is typically used when we ask for information about a user’s country in the website’s login form or navigation bar. To maintain the accessibility of the website, we often use the label tag to make it accessible and better for end users.

image

What are the various select tag attributes?

HTML attributes are unique keywords used within the opening tag to regulate the element’s behavior. HTML attributes are a type of modifier for an HTML element. The attributes provide additional information about HTML elements.

The select tag has various characteristics, including:

  • Autofocus (Type — Boolean): The HTML < select > autofocus attribute is used to specify that the dropdown should automatically get focused when the page loads or when the user reaches a certain viewport.

  • Required (Type — Boolean): The HTML < input > required attribute indicates that the user must select a value before submitting the form. The required attribute is a boolean attribute. A variety of input types support the required attribute, including text, search, URL, tel, email, password, date pickers, numbers, checkboxes, radios, and files.

  • Multiple (Type — Boolean): The HTML multiple attributes specify that the user is allowed to select more than one option (or value) from the given list of options inside the < select > element. Additionally, it can work with the < input > tag.

  • Disabled (Type — Boolean): To indicate that a select element is disabled, we use the disabled attribute. A drop-down list that is disabled cannot be used or clicked on. It is also a boolean attribute.

  • Name (Type — String): The drop-down list’s name is specified using the name attribute. It can reference an element in JavaScript or the form data after submitting it.

<img
      src="A Link to an image or any local image "
      alt="an alternative test if the browser can't display the image"
      width="104"
      height="142"  />
Enter fullscreen mode Exit fullscreen mode

We can see a few of the < img > element’s attributes in this example. These attributes give additional information to the < img > element. There are more than 12 attributes for the < img > tag.

Here we have used attributes like src, which corresponds to the image’s source/link, alt, which provides a meaning-filled text description to increase accessibility, and height and width, which describe the image’s height and width.

 <!-- input form with all attributes  -->
   <form>
    <label for="fname"> First name:</label><br />
    <input type="text" id="fname" name="fname" value="John" /><br />
    <label for="lname">Last name:</label><br />
    <input type="text" id="lname" name="lname" value="Doe" /><br /><br />
    <input type="submit" value="Submit" />
    <select name="Mobile" id="Mobiles">
      <option value="Samsung">Samsung</option>
      <option value="Apple">Apple</option>
      <option value="OnePlus">OnePlus</option>
      <option value="Xiaomi">Xiaomi</option>
      <option value="Oppo">Oppo</option>
      <option value="Vivo">Vivo</option>
    </select>
  </form>
Enter fullscreen mode Exit fullscreen mode

The use of several HTML attributes can be seen in the examples above, including action, which specifies the action to be taken when the form is submitted, If the action attribute is omitted, then the default action will be set to the current page.

The name attribute corresponds to the name of the current element as defined by the user, id, which is a unique user-defined name, and value, which is used differently for various input types, such as text for buttons and the initial value for < input > elements.

Other attributes include style, class, and other global attributes that can be used with all HTML elements and some specific to certain HTML elements, such as href and defer.

We won’t go into great detail about HTML attributes because that is outside the scope of this blog on CSS Select, but it is crucial to take accessibility, providing meaningful descriptions via attributes, and following best practices into consideration.

Through this usability testing tutorial, you will learn how usability testing is a great way to discover unexpected bugs, find what is unnecessary or unused before going any further, and have unbiased opinions from an outsider.

Dropdowns vs. Select vs. Menu vs. Navigation

One common misunderstanding among novice developers is the names mentioned while discussing dropdowns. The most common of which are dropdown, select, and menu.

In this section of the CSS Select blog, let’s have a closer look at what they are.

Dropdown

An interactive element made up of a button that, typically on mouse hover, click, or tap, reveals and conceals a list of items. Before the beginning of the interaction, the list is hidden by default.

A drop-down list only shows one value when it is not active. When the user interacts with the dropdown, a list of values is displayed for the user to choose from.

image

Material UI Dropdown

A form control that shows a list of choices on a form for the user to select a single item or multiple items.

To make a drop-down list, we use the HTML < select > element. The < select > element is most frequently used in forms for gathering user inputs.

Menu

The < menu > tag defines a list/menu of commands or actions that can be performed on a website.

Currently, the < menu > tag is supported in Firefox, and it doesn’t work on popular browsers like Chrome, Internet Explorer, Safari, and Opera Mini. Presently, it has been removed from the HTML5 standards.

image

Navigation

A navigation menu on a website is a structured set of connections to other web pages, typically internal sites.

Navigation menus are most frequently found in page headers or sidebars, allowing users to rapidly reach the most important pages on a website.

image

How to construct a basic HTML Select field?

This section of this blog on CSS Select will discuss the basic aspects of web design involved in the HTML Select element and how to use CSS to style it.

First, the < select > tag is often used when we need to get user input, and the user is given various options to choose from. It may resemble selecting various states or nations, or it might even resemble using a dropdown to switch between pages.

Below is the source code for constructing a select section.

HTML:

<select name="Phone" id="Phone">
  <option value="Realme">Realme</option>
  <option value="Redmi">Redmi</option>
  <option value="Iphone">Iphone</option>
  <option value="Samsung">Samsung</option>
    <option value=”Pixels">Google Pexels</option>
</select>
Enter fullscreen mode Exit fullscreen mode

Output:

<html>
  <body>
  <select name="Phone" id="Phone">
  <option value="Realme">Realme</option>
  <option value="Redmi">Redmi</option>
  <option value="Iphone">Iphone</option>
  <option value="Samsung">Samsung</option>
    <option value="OPPO">OPPO</option>
    <option value="Google Pexel">Google Pixel</option>

</select>

  <select name="Phone" id="Phone">
      <option value="Chrome">Chrome</option>
      <option value="Firefox">Firefox</option>
      <option value="Safari">Safari</option>
      <option value="Edge">Edge </option>
    </select>



</body>

</html>
Enter fullscreen mode Exit fullscreen mode

The output of the code looks as follows:

image

This is straightforward and is a good place to begin. Let’s now add custom CSS to make it look good as well as design friendly.

CSS:

select{
    width: 10%;
    height: 50px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding-left: 5px;
    padding: 10px;
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    color: #555;
    background-color: rgb(255, 255, 255);
    background-image: none;
    border: 1px solid rgb(41, 18, 18);
}
select>option{
    font-size: 18px;
    font-family: 'Open Sans', sans-serif;
    color: #555;
    background-color: rgb(247, 247, 247);
    background-image: none;
    font-size: 18px;
    height: 50px;
    padding: 15px;
    border: 1px solid rgb(41, 18, 18);
}
Enter fullscreen mode Exit fullscreen mode

Output:

image

Black Box testing? Don’t worry; we will be covering what is Black box testing, merits, demerits, types & techniques.

Despite having styles applied to it, the < select > tag’s styles hardly ever change. This is because they are not usual DOM elements, making them behave differently from others.

For developers, the < select > and < option > elements are the most frustrating form controls due to their lack of styling support. This is because they are rendered by the operating system, not HTML.There are only a few style attributes that can be applied to the < option >. Because of how much of a UX battle it is, we will look into other solutions.

image

The above image makes it clear that applying styles to the < option > tag does not work as intended. The events like click or keypress on tag do not function because the browser generates them outside the DOM model.

A consistent way to mark up the functionality of a list of selectable options is provided by the < select > element. Nevertheless, the browser has complete control over how that list is displayed and can do so most effectively considering the operating system, browser, and current device.

Since we can never be certain how it will be presented, trying to style it in any way may not be effective. We can look into some examples where we test how select tags are presented for different browsers, operating systems, etc.

HTML:

<html>
  <body>
    <select name="Phone" id="Phone">
      <option value="Realme">Realme</option>
      <option value="Redmi">Redmi</option>
      <option value="Iphone">Iphone</option>
      <option value="Samsung">Samsung</option>
      <option value="OPPO">OPPO</option>
      <option value="Google Pexel">Google Pixel</option>
    </select>

    <select name="Phone" id="Phone">
      <option value="Chrome">Chrome</option>
      <option value="Firefox">Firefox</option>
      <option value="Safari">Safari</option>
      <option value="Edge">Edge</option>
    </select>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output (macOS):

<html>
  <body>
  <select name="Phone" id="Phone">
  <option value="Realme">Realme</option>
  <option value="Redmi">Redmi</option>
  <option value="Iphone">Iphone</option>
  <option value="Samsung">Samsung</option>
    <option value="OPPO">OPPO</option>
    <option value="Google Pexel">Google Pixel</option>

</select>

  <select name="Phone" id="Phone">
      <option value="Chrome">Chrome</option>
      <option value="Firefox">Firefox</option>
      <option value="Safari">Safari</option>
      <option value="Edge">Edge </option>
    </select>



</body>

</html>
Enter fullscreen mode Exit fullscreen mode
<html>
  <body>
  <select name="Phone" id="Phone">
  <option value="Realme">Realme</option>
  <option value="Redmi">Redmi</option>
  <option value="Iphone">Iphone</option>
  <option value="Samsung">Samsung</option>
    <option value="OPPO">OPPO</option>
    <option value="Google Pexel">Google Pixel</option>

</select>

  <select name="Phone" id="Phone">
      <option value="Chrome">Chrome</option>
      <option value="Firefox">Firefox</option>
      <option value="Safari">Safari</option>
      <option value="Edge">Edge </option>
    </select>



</body>

</html>
Enter fullscreen mode Exit fullscreen mode

We can see that the < select > tag is rendered differently. This can be an issue for users if we develop a web application that only considers a particular browser or operating system. We must consider all the major operating systems and browsers to ensure that our application is compatible with cross-browser.

We now comprehend the need for customized CSS Select menus, so let’s start creating those.

How to create a custom dropdown menu with CSS Select?

In this section, we will look at how to create dropdown menus using CSS Select.

There are numerous ways to create a dropdown menu. We can either use CSS to make custom dropdowns or the native select tag to create dropdown menus. All we have to do is to use appropriate HTML elements and then style them accordingly.

We can use CSS Select to its full potential to make custom drop-down elements. With drop-down menus, users can quickly access your site’s content without scrolling. Drop-down menus can save users time by allowing them to jump down a level or two to find the content they want.

A good example of dropdowns in use is in e-commerce websites, where users will see dropdown inputs during checkout. Let’s now create some custom dropdown menus.

This smoke testing tutorial covers what smoke testing is, its importance, benefits, and how to perform it with real-time examples.

Creating custom dropdown menus with Grid layout

In this first example of this blog on CSS Select, using the standard < select > tag and custom CSS, we can now walk through the code for creating dropdowns that can be controlled using the attributes.

The disabled attribute specifies whether the element should be disabled or not. The multiple attributes specify that the user is allowed to select more than one value. Additionally, we have added styling-related attributes like id and class.

Here we use the CSS Grid layout for creating drop-downs. Grid is a CSS property that handles the layout in a two-dimensional grid system with columns and rows. Elements can be placed on the grid within these column and row lines. Since we have full control of where to place the item, this property makes the grid ideal for creating drop-downs.

Using the native < select > tag present in HTML, we will create dropdowns that can be controlled by altering attributes like disabled, multiple, etc.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>


<label for="standard-select">Default Select Menu </label>
<div class="select">
  <select id="standard-select">
    <option value="Option 1">Twitter </option>
    <option value="Option ">Facebook</option>
    <option value="Option 3">Reddit </option>
    <option value="Option 4">Youtube </option>

  </select>
  <span class="focus"></span>
</div>

<label for="multi-select">Multiple Selection</label>
<div class="select select--multiple">
  <select id="multi-select" multiple>
    <option value="Option 1">Web Development </option>
    <option value="Option 2">App Development </option>
    <option value="Option 3"> Machine Learning</option>
    <option value="Option 4">Automation </option>
    <option value="Option 5"> AI</option>
    <option value="Option length">Some other</option>
  </select>
  <span class="focus"></span>
</div>

<label for="standard-select-disabled">Disabled Select</label>
<div class="select select--disabled">
  <select id="standard-select-disabled" disabled>
    <option value="Option 1">Server side rendering</option>
    <option value="Option 2">Client side rendering</option>
    <option value="Option 3">Static site generation</option>
    <option value="Option 4">Hybrid Site Generator</option>
    <option value="Option 5">Server + Client side rendering</option>
    <option value="Option length">Single Page Application</option>
  </select>
</div>

<label for="standard-select">Disabled Multiple Select</label>
<div class="select select--disabled select--multiple">
  <select id="multi-select-disabled" multiple disabled>
    <option value="Option 1">React JS</option>
    <option value="Option 2">AngularJS</option>
    <option value="Option 3">Meteor JS</option>
    <option value="Option 4">Svelte Kit </option>
    <option value="Option 5">Hydrogen JS</option>
    <option value="Option length">React JS with NextJS </option>
  </select>
</div>


</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

body {
  background-color: red;
}
:root {
  --select-border: #777;
  --select-focus: #00f;
  --select-arrow: var(--select-border);
}
select {
  appearance: none;
  background-color: transparent;
  border: none;
  padding: 0 1em 0 0;
  margin: 0;
  width: 100%;
  font-family: inherit;
  font-size: inherit;
  cursor: inherit;
  line-height: inherit;
  z-index: 1;
  outline: none;
}

.select {
  display: grid;
  grid-template-areas: "select";
  align-items: center;
  position: relative;
  min-width: 15ch;
  max-width: 30ch;
  border: 1px solid var(--select-border);
  border-radius: 0.25em;
  padding: 0.25em 0.5em;
  font-size: 1.25rem;
  cursor: pointer;
  line-height: 1.1;
  background-color: #fff;
  background-image: linear-gradient(to top, #f9f9f9, #fff 33%);
}
.select select,
.select::after {
  grid-area: select;
}
.select:not(.select--multiple)::after {
  content: "";
  justify-self: end;
  width: 0.8em;
  height: 0.5em;
  background-color: var(--select-arrow);
  clip-path: polygon(100% 0%, 0 0%, 50% 100%);
}
select:focus + .focus {
  position: absolute;
  top: -1px;
  left: -1px;
  right: -1px;
  bottom: -1px;
  border: 2px solid var(--select-focus);
  border-radius: inherit;
}
select[multiple] {
  padding-right: 0;

  height: 6rem;

}
select[multiple] option {
  white-space: normal;
  outline-color: var(--select-focus);
}
.select--disabled {
  cursor: not-allowed;
  background-color: #eee;
  background-image: linear-gradient(to top, #ddd, #eee 33%);
}
label {
  font-size: 1.125rem;
  font-weight: 500;
}
.select + label {
  margin-top: 2rem;
}
body {
  min-height: 100vh;
  display: grid;
  place-content: center;
  grid-gap: 0.5rem;
  font-family: "Baloo 2", sans-serif;
  background-color: skyblue;
  padding: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

Output:

<label for="standard-select">Default Select Menu </label>
<div class="select">
  <select id="standard-select">
    <option value="Option 1">Twitter </option>
    <option value="Option ">Facebook</option>
    <option value="Option 3">Reddit </option>
    <option value="Option 4">Youtube </option>

  </select>
  <span class="focus"></span>
</div>

<label for="multi-select">Multiple Selection</label>
<div class="select select--multiple">
  <select id="multi-select" multiple>
    <option value="Option 1">Web Development </option>
    <option value="Option 2">App Development </option>
    <option value="Option 3"> Machine Learning</option>
    <option value="Option 4">Automation </option>
    <option value="Option 5"> AI</option>
    <option value="Option length">Some other</option>
  </select>
  <span class="focus"></span>
</div>

<label for="standard-select-disabled">Disabled Select</label>
<div class="select select--disabled">
  <select id="standard-select-disabled" disabled>
    <option value="Option 1">Server side rendering</option>
    <option value="Option 2">Client side rendering</option>
    <option value="Option 3">Static site generation</option>
    <option value="Option 4">Hybrid Site Generator</option>
    <option value="Option 5">Server + Client side rendering</option>
    <option value="Option length">Single Page Application</option>
  </select>
</div>

<label for="standard-select">Disabled Multiple Select</label>
<div class="select select--disabled select--multiple">
  <select id="multi-select-disabled" multiple disabled>
    <option value="Option 1">React JS</option>
    <option value="Option 2">Angular JS</option>
    <option value="Option 3">Meteor JS</option>
    <option value="Option 4">Svelte Kit </option>
    <option value="Option 5">Hydrogen JS</option>
    <option value="Option length">React JS with NextJS </option>
  </select>
</div>
Enter fullscreen mode Exit fullscreen mode

The disabled attribute can be used to prevent a user from accessing the drop-down list unless another condition is met (like selecting a checkbox, etc.). The disabled value can then be removed using JavaScript, making the drop-down list usable. The multiple attribute allows the user to select multiple items from a list, which is ideal when the user needs to have multiple items checked, such as choosing multiple genres from Spotify.

Creating custom select menus with input elements

In the following example, select menus will be made using the < input > tag. The < input > tag is commonly used to collect data from users. < input > tags come in various forms to accommodate the various ways users can select, add, and filter data.

Some of the types of < input > tags are shown in the below example.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <style>
    .input{
      display: flex;
      flex-wrap: wrap;
    }
    input{
      width: 25%;
      margin: 10px;
      height: 25px;
    }
  </style>
  <!-- All input tags with styles -->
  <div class="input">
    <input type="text" placeholder="Text">
    <input type="email" placeholder="Email">
    <input type="password" placeholder="Password">
    <input type="number" placeholder="Number">
    <input type="date" placeholder="Date">
    <input type="time" placeholder="Time">
    <input type="color" placeholder="Color">
    <input type="file" placeholder="File">
    <input type="submit" placeholder="Submit">
    <input type="reset" placeholder="Reset">
    <input type="button" name="Button" value="Button" placeholder="Button">
    <input type="checkbox" placeholder="Checkbox">
    <input type="radio" placeholder="Radio">
    <input type="range" placeholder="Range">
    <input type="search" placeholder="Search">
    <input type="tel" placeholder="Tel">
    <input type="url" placeholder="Url">
    <input type="week" placeholder="Week">
    <input type="month" placeholder="Month">
    <input type="datetime-local" placeholder="Datetime-local">
  </div>
 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output:

image

image

Let’s now use CSS to position the menu items and convert the radio button, a type of input button, into a custom Select box.

In input forms, radio buttons are commonly used to select a value from available options, such as choosing the corresponding gender. Here, we’ll use CSS to customize this functionality to become a selectable dropdown.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="index.css" />
  </head>
  <body>
    <div id="info">Which is the most developer friendly platform?</div>

    <form id="form__cover">
      <div id="select-box">
        <input type="checkbox" id="options-view-button" />
        <div id="select-button" class="section">
          <div id="selected-value">
            <span>Select a platform</span>
          </div>
        </div>
        <div id="options">
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="Github"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="Github"
            />
            <span class="label">Github</span>
            <span class="opt-val">Github</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="Youtube"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="Youtube"
            />
            <span class="label">Youtube</span>
            <span class="opt-val">Youtube</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="W3School"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="W3School"
            />
            <span class="label">W3Schools</span>
            <span class="opt-val">W3Schools</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="LeetCode"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="LeetCode"
            />
            <span class="label">LeetCode</span>
            <span class="opt-val">LeetCode</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="stackoverflow"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="stackoverflow"
            />
            <span class="label">StackOverflow</span>
            <span class="opt-val">StackOverflow</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="freecodecamp"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="freecodecamp"
            />

            <span class="label">FreeCodeCamp</span>
            <span class="opt-val">FreeCodeCamp</span>
          </div>
          <div id="option-bg"></div>
        </div>
      </div>
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

  * {
    user-select: none;
  }

  *:focus {
    outline: none;
  }

  html,
  body {
    height: 100%;
    min-height: 100%;

  }

  body {
    font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    padding-bottom: 100px;
    margin: 0;
    background-color: black;  }

  .section {
    border: 1px solid #e2eded;
    border-color: #eaf1f1 #e4eded #dbe7e7 #e4eded;
  }

  #info {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    color: #2d3667;
    font-size: 16px;
    text-align: center;
    padding: 14px;
    background-color: #f3f9f9;
  }

  #form__cover {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    width: 300px;
    height: 42px;
    margin: 100px auto 0 auto;
    z-index: 1;
  }

  #select-button {
    position: relative;
    height: 16px;
    padding: 12px 14px;
    background-color: rgb(247, 247, 247);
    border-radius: 4px;
    border: 1px solid gray;
    cursor: pointer;
  }

  #options-view-button {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    margin: 0;
    opacity: 0;
    cursor: pointer;
    z-index: 3;
  }

  #selected-value {
    font-size: 16px;
    line-height: 1;
    margin-right: 26px;
  }



  .option,
  .label {
    color: #2d3667;
    font-size: 16px;
  }


  #options-view-button:checked + #select-button #chevrons i {
    color: #2d3667;
  }

  .options {
    position: absolute;
    left: 0;
    width: 250px;
  }

  #options {
    position: absolute;
    top: 42px;
    right: 0;
    left: 0;
    width: 298px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 4px;
  }

  #options-view-button:checked ~ #options {
    border: 1px solid #e2eded;
    border-color: #eaf1f1 #e4eded #dbe7e7 #e4eded;
  }

  .option {
    position: relative;
    line-height: 1;
    transition: 0.3s ease all;
    z-index: 2;
  }

  .option i {
    position: absolute;
    left: 14px;
    padding: 0;
    display: none;
  }

  #options-view-button:checked ~ #options .option i {
    display: block;
    padding: 12px 0;
  }

  .label {
    display: none;
    padding: 0;
    margin-left: 27px;
  }

  #options-view-button:checked ~ #options .label {
    display: block;
    padding: 12px 14px;
  }

  .s-c {
    position: absolute;
    left: 0;
    width: 100%;
    height: 50%;
  }

  .s-c.top {
    top: 0;
  }

  .s-c.bottom {
    bottom: 0;
  }

  input[type="radio"] {
    position: absolute;
    right: 0;
    left: 0;
    width: 100%;
    height: 50%;
    margin: 0;
    opacity: 0;
    cursor: pointer;
  }

  .s-c:hover ~ i {
    color: #fff;
    opacity: 0;
  }

  .s-c:hover {
    height: 100%;
    z-index: 1;
  }

  .s-c.bottom:hover + i {
    bottom: -25px;
    animation: moveup 0.3s ease 0.1s forwards;
  }

  .s-c.top:hover ~ i {
    top: -25px;
    animation: movedown 0.3s ease 0.1s forwards;
  }

  @keyframes moveup {
    0% {
      bottom: -25px;
      opacity: 0;
    }
    100% {
      bottom: 0;
      opacity: 1;
    }
  }

  @keyframes movedown {
    0% {
      top: -25px;
      opacity: 0;
    }
    100% {
      top: 0;
      opacity: 1;
    }
  }

  .label {
    transition: 0.3s ease all;
  }

  .opt-val {
    position: absolute;
    left: 14px;
    width: 217px;
    height: 21px;
    opacity: 0;
    background-color: rgb(247, 247, 247);
    transform: scale(0);
  }

  .option input[type="radio"]:checked ~ .opt-val {
    opacity: 1;
    transform: scale(1.01);
  }

  .option input[type="radio"]:checked ~ i {
    top: 0;
    bottom: auto;
    opacity: 1;
    animation: unset;
  }

  .option input[type="radio"]:checked ~ i,
  .option input[type="radio"]:checked ~ .label {
    color: #fff;
  }

  .option input[type="radio"]:checked ~ .label:before {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: -1;
  }

  #options-view-button:not(:checked)
    ~ #options
    .option
    input[type="radio"]:checked
    ~ .opt-val {
    top: -30px;
  }

  .option:nth-child(1) input[type="radio"]:checked ~ .label:before {
    background-color: #000;
    border-radius: 4px 4px 0 0;
  }

  .option:nth-child(1) input[type="radio"]:checked ~ .opt-val {
    top: -31px;
  }

  .option:nth-child(2) input[type="radio"]:checked ~ .label:before {
    background-color: #f70800;
  }

  .option:nth-child(2) input[type="radio"]:checked ~ .opt-val {
    top: -71px;
  }

  .option:nth-child(3) input[type="radio"]:checked ~ .label:before {
    background-color: #09ff00;
  }

  .option:nth-child(3) input[type="radio"]:checked ~ .opt-val {
    top: -111px;
  }

  .option:nth-child(4) input[type="radio"]:checked ~ .label:before {
    background-color: #f18203;
  }

  .option:nth-child(4) input[type="radio"]:checked ~ .opt-val {
    top: -151px;
  }

  .option:nth-child(5) input[type="radio"]:checked ~ .label:before {
    background-color: #b6590c;
  }

  .option:nth-child(5) input[type="radio"]:checked ~ .opt-val {
    top: -191px;
  }

  .option:nth-child(6) input[type="radio"]:checked ~ .label:before {
    background-color: black;
    border-radius: 0 0 4px 4px;
  }

  .option:nth-child(6) input[type="radio"]:checked ~ .opt-val {
    top: -231px;
  }


  #option-bg {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    height: 40px;
    transition: 0.3s ease all;
    z-index: 1;
    display: none;
  }

  #options-view-button:checked ~ #options #option-bg {
    display: block;
  }

  .option:hover .label {
    color: #fff;
  }

  .option:nth-child(1):hover ~ #option-bg {
    top: 0;
    background-color: #000;
    border-radius: 4px 4px 0 0;
  }

  .option:nth-child(2):hover ~ #option-bg {
    top: 40px;
    background-color: #f70800;
  }

  .option:nth-child(3):hover ~ #option-bg {
    top: 80px;
    background-color: #09ff00;
  }

  .option:nth-child(4):hover ~ #option-bg {
    top: 120px;
    background-color: #ff7300;
  }

  .option:nth-child(5):hover ~ #option-bg {
    top: 160px;
    background-color: #b6590c;
  }

  .option:nth-child(6):hover ~ #option-bg {
    top: 200px;
    background-color: black;
Enter fullscreen mode Exit fullscreen mode

Output:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="index.css" />
  </head>
  <body>
    <div id="info">Which is the most developer friendly platform?</div>

    <form id="form__cover">
      <div id="select-box">
        <input type="checkbox" id="options-view-button" />
        <div id="select-button" class="section">
          <div id="selected-value">
            <span>Select a platform</span>
          </div>
        </div>
        <div id="options">
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="Github"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="Github"
            />
            <span class="label">Github</span>
            <span class="opt-val">Github</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="Youtube"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="Youtube"
            />
            <span class="label">Youtube</span>
            <span class="opt-val">Youtube</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="W3School"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="W3School"
            />
            <span class="label">W3Schools</span>
            <span class="opt-val">W3Schools</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="LeetCode"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="LeetCode"
            />
            <span class="label">LeetCode</span>
            <span class="opt-val">LeetCode</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="stackoverflow"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="stackoverflow"
            />
            <span class="label">StackOverflow</span>
            <span class="opt-val">StackOverflow</span>
          </div>
          <div class="option">
            <input
              class="s-c top"
              type="radio"
              name="platform"
              value="freecodecamp"
            />
            <input
              class="s-c bottom"
              type="radio"
              name="platform"
              value="freecodecamp"
            />

            <span class="label">FreeCodeCamp</span>
            <span class="opt-val">FreeCodeCamp</span>
          </div>
          <div id="option-bg"></div>
        </div>
      </div>
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Creating a custom dropdown with CSS Flexbox

To make the select menu more user-friendly, let’s now put our CSS skills to use by positioning the dropdown elements using different CSS properties like position and flexbox.

CSS Flexbox is a layout that simplifies the creation of flexible, responsive layout structures without using float or position properties. Flexbox handles layout in only one dimension at a time, either row or column. This makes Flexbox great for customized drop-downs with HTML divs and spans since we can set the flex-direction property to make it appear as a drop-down.

We are free to modify the dropdown so that it complements the design aspects of the website.

In this System testing tutorial, learn why System testing is important and all the intricacies of the System testing process.

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div class="select" tabindex="1">
      <input class="selectopt" name="test" type="radio" id="option1" checked />
      <label for="option1" class="option">Youtube</label>
      <input class="selectopt" name="test" type="radio" id="option2" />
      <label for="option2" class="option">Twitch</label>
      <input class="selectopt" name="test" type="radio" id="option3" />
      <label for="option3" class="option">TikTok</label>
      <input class="selectopt" name="test" type="radio" id="option4" />
      <label for="option4" class="option">Instagram Reels</label>
      <input class="selectopt" name="test" type="radio" id="option5" />
      <label for="option5" class="option">Youtube Shorts</label>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

body {
  background:#ae15eb;
  display:flex;
  justify-content: center;
  align-items:center;
  flex-wrap:wrap;
  padding:0;
  margin:0;
  height:100vh;
  width:100vw;
  font-family: sans-serif;
  color:#FFF;
}
.select {
  display:flex;
  flex-direction: column;
  position:relative;
  width:350px;
  height:100px;
}
.option {
  padding:0 30px 0 10px;
  min-height:40px;
  display:flex;
  align-items:center;
  background:rgb(9, 184, 67);
  border-top:#222 solid 1px;
  position:absolute;
  top:0;
  width: 100%;
  pointer-events:none;
  order:2;
  z-index:1;
  transition:background .4s ease-in-out;
  box-sizing:border-box;
  overflow:hidden;
  white-space:nowrap;

}
.option:hover {
  background:rgb(8, 145, 26);
}

.select:focus .option {
  position:relative;
  pointer-events:all;
}

input {
  opacity:1;
  position:absolute;
  left:99px;
}

input:checked + label {
  order: 2;
  z-index:2;
  background:#666;
  border-top:none;
  position:relative;
}

input:checked + label:after {
  content:'';
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid white;
  position:absolute;
  right:10px;
  top:calc(50% - 2.5px);
  pointer-events:none;
  z-index:3;
}

input:checked + label:before {
  position:absolute;
  right:0;
  height: 40px;
  width: 40px;
  content: '';
  background:#666;
}

@media screen and (max-width: 600px) {
  .select {
    width:90%;
  }
Enter fullscreen mode Exit fullscreen mode

Output:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <div class="select" tabindex="1">
      <input class="selectopt" name="test" type="radio" id="option1" checked />
      <label for="option1" class="option">Youtube</label>
      <input class="selectopt" name="test" type="radio" id="option2" />
      <label for="option2" class="option">Twitch</label>
      <input class="selectopt" name="test" type="radio" id="option3" />
      <label for="option3" class="option">TikTok</label>
      <input class="selectopt" name="test" type="radio" id="option4" />
      <label for="option4" class="option">Instagram Reels</label>
      <input class="selectopt" name="test" type="radio" id="option5" />
      <label for="option5" class="option">Youtube Shorts</label>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Filtering options in a dropdown list with JavaScript

We can utilize the CSS properties like Flexbox and Grid to make the layout for our select menu.

Flexbox is a CSS layout that simplifies the creation of flexible, responsive layout structures without using float or position properties. Flexbox handles layout in only one dimension at a time, either row or column. This makes flexbox great for customized drop-downs with HTML divs and spans since we can set the flex-direction property to make it appear as a drop-down.

We make use of CSS Media Queries to make our dropdown responsive. We must consider standard device dimensions like 480 pixels, 640 pixels, 720 pixels, 1024 pixels, 1440 pixels, etc. The main objective of responsive websites is to ensure a seamless experience across different digital devices. The majority of today’s libraries and frameworks take this technique. Thus we should do the same while creating custom dropdowns.

We have created custom Select menus using a variety of CSS properties, such as Flexbox, Grid, and positioning, and now it is time to put our true creativity to work, creating custom select menus with CSS, also with the help of JavaScript.

JavaScript is being used in this case to create filterable options, which means that as the user types, the other options that are not similar to the given input in the options list are removed. The logic used here is plain and simple. We have an array of list items; whenever the user enters a specific character or group of characters, we iterate through the list and determine whether the entered input is present in the list of items. If it is not present, we remove those items from the dropdown list, giving the user a filtered and small list.

This is handy when users have to select from a long list like a list of countries, states, etc.

A complete Manual testing tutorial covering all aspects of Manual testing, including strategies and best practices.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="index.css"/>
  <script src="inde.js" defer></script>

</head>
<body>
  <h1> <span>filterable</span> select dropdown</h1>
  <form>
    <input
      class="chosen-value"
      type="text"
      value=""
      placeholder="Type to filter"
    />
    <ul class="value-list">
      <!-- List of tech giants -->
      <li>Elon Musk</li>
      <li>Bill Gates</li>
      <li>Steve Jobs</li>
      <li>Mark Zuckerberg</li>
      <li>Larry Page</li>
      <li>Sergey Brin</li>
      <li>Larry Ellison</li>
      <li>Jack Dorsey</li>
      <li>Jeff Bezos</li>
      <li>Paul Allen</li>
      <li>Jack Ma</li>
      <li>Dan Abranoah</li>
      <li>Jordan Walkie</li>
      <li>Satya Nadella</li>
      <li>Kunal Shah</li>
<li> Asad Khan </li>
<li> Jay Singh </li>
    </ul>
  </form>


</body>
</html>



CSS:
** {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  align-items: center;
  justify-content: flex-start;
  font-family: 'Ek Mukta';
  text-transform: uppercase;
  font-weight: 600;
  letter-spacing: 4px;
  background: #1D1F20;
}
h1 {
  margin-top: 10vh;
  font-size: 2.5rem;
  max-width: 500px;
  letter-spacing: 3px;
  text-align: center;
  line-height: 1.5;
  font-family: 'Open Sans';
  text-transform: capitalize;
  font-weight: 800;
  color: white;
}
h1 span {
  color: #0010f1;
}
form {
  position: relative;
  width: 25rem;
  margin-top: 12vh;
}
@media screen and (max-width: 768px) {
  form {
    width: 90%;
  }


}
.chosen-value, .value-list {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
.chosen-value {
  font-family: 'Ek Mukta';
  text-transform: uppercase;
  font-weight: 600;
  letter-spacing: 4px;
  height: 4rem;
  font-size: 1.1rem;
  padding: 1rem;
  background-color: #FAFCFD;
  border: 3px solid transparent;
  transition: 0.3s ease-in-out;
}
.chosen-value::-webkit-input-placeholder {
  color: #333;
}
.chosen-value:hover {
  background-color: #0844eb;
  cursor: pointer;
}
.chosen-value:hover::-webkit-input-placeholder {
  color: #333;
}
.chosen-value:focus, .chosen-value.open {
  box-shadow: 0px 5px 8px 0px rgba(0, 0, 0, 0.2);
  outline: 0;
  background-color: #2912f7;
  color: #000;
}
.chosen-value:focus::-webkit-input-placeholder, .chosen-value.open::-webkit-input-placeholder {
  color: #000;
}
.value-list {
  list-style: none;
  margin-top: 4rem;
  box-shadow: 0px 5px 8px 0px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  max-height: 0;
  transition: 0.3s ease-in-out;
}
.value-list.open {
  max-height: 320px;
  overflow: auto;
}
.value-list li {
  position: relative;
  height: 4rem;
  background-color: #FAFCFD;
  padding: 1rem;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s;
  opacity: 1;
}
.value-list li:hover {
  background-color: #450ae9;
  color: white;
}
.value-list li.closed {
  max-height: 0;
  overflow: hidden;
  padding: 0;
  opacity: 0;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const inputField = document.querySelector('.chosen-value');
const dropdown = document.querySelector('.value-list');
const dropdownArray = [... document.querySelectorAll('li')];

dropdown.classList.add('open');
inputField.focus(); 
let valueArray = [];
dropdownArray.forEach(item => {
  valueArray.push(item.textContent);
});


const closeDropdown = () => {
  dropdown.classList.remove('open');
}

inputField.addEventListener('input', () => {
  dropdown.classList.add('open');
  let inputValue = inputField.value.toLowerCase();
  let valueSubstring;
  if (inputValue.length > 0) {
    for (let j = 0; j < valueArray.length; j++) {
      if (!(inputValue.substring(0, inputValue.length) === valueArray[j].substring(0, inputValue.length).toLowerCase())) {
        dropdownArray[j].classList.add('closed');
      } else {
        dropdownArray[j].classList.remove('closed');
      }
    }
  } else {
    for (let i = 0; i < dropdownArray.length; i++) {
      dropdownArray[i].classList.remove('closed');
    }
  }
});

dropdownArray.forEach(item => {
  item.addEventListener('click', (evt) => {
    inputField.value = item.textContent;
    dropdownArray.forEach(dropdown => {
      dropdown.classList.add('closed');
    });
  });
})

inputField.addEventListener('focus', () => {
   inputField.placeholder = 'Type to filter';
   dropdown.classList.add('open');
   dropdownArray.forEach(dropdown => {
     dropdown.classList.remove('closed');
   });
});

inputField.addEventListener('blur', () => {
   inputField.placeholder = 'Select Favorite Techie';
  dropdown.classList.remove('open');
});


document.addEventListener('click', (evt) => {
  const isDropdown = dropdown.contains(evt.target);
  const isInput = inputField.contains(evt.target);
  if (!isDropdown && !isInput) {
    dropdown.classList.remove('open');
  }   
});
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

</head>
<body>
  <h1> <span>filterable</span> select dropdown</h1>
  <form>
    <input
      class="chosen-value"
      type="text"
      value=""
      placeholder="Type to filter"
    />
    <ul class="value-list">
      <!-- List of tech giants -->
      <li>Elon Musk</li>
      <li>Bill Gates</li>
      <li>Steve Jobs</li>
      <li>Mark Zuckerberg</li>
      <li>Larry Page</li>
      <li>Sergey Brin</li>
      <li>Larry Ellison</li>
      <li>Jack Dorsey</li>
      <li>Jeff Bezos</li>
      <li>Paul Allen</li>
      <li>Jack Ma</li>
      <li>Dan Abranoah</li>
      <li>Jordan Walkie</li>
      <li>Satya Nadella</li>
      <li>Kunal Shah</li>
    </ul>
  </form>


</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Creating a fully custom dropdown list

Now that we’ve covered a variety of techniques for building custom Select menus using CSS and JavaScript to add interactivity, we can use both of these technologies and our creativity to create custom CSS Select options that are much more user-friendly.

Here, we’re going to create an interactive select menu where the user can choose the value more effectively based on his preferences.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="index.css"/>
  <script  src="index.js" defer>
  </script>

</head>
<div>
  <div class="wrapper typo">The best browser is
    <div class="list"><span class="placeholder">FireFox </span>
      <ul class="list__ul">
        <li><a href="#"> Chrome</a></li>
        <li><a href="#">Brave </a></li>
        <li><a href="#">Chromium </a></li>
        <li><a href="#">Safari</a></li>
        <li><a href="#">Opera Mini</a></li>
        <li><a href="#">UC Browser</a></li>
      </ul>
    </div>

  </div>
</div>
</body>
</html>

>
Enter fullscreen mode Exit fullscreen mode

CSS:

 @import url('https://fonts.googleapis.com/css?family=Poppins&display=swap');

 body{
   background: rgb(26, 23, 23);
 }

 .typo, .list a {
   font-size: 50px;
   font-weight: 700;
   font-family: 'Poppins', serif;
   color: #ffffff;
   text-decoration: none;
 }
 .typo option, .list a option {
   font-size: 30px;
 }
 .transition {
   transition: all 0.4s ease-in-out;
 }
 body {
   text-align: center;
   display: flex;
   align-items: center;
   justify-content: center;
   height: 100vh;
 }
 .wrapper {
   font-size: 60px;
   margin-top: -10%;
 }
 .list {
   display: inline-block;
   position: relative;
   margin-left: 6px;
 }
 .list ul {
   text-align: left;
   position: absolute;
   padding: 0;
   top: 0;
   left: 0;
   display: none;
 }
 .list ul .active {
   display: block;
 }
 .list li {
   list-style: none;
 }
 .list li:first-child a {
   color: #00eb0c;
 }
 .list a {
   transition: all 0.4s;
   color: #00ff40;
   position: relative;
 }
 .list a:after {
   position: absolute;
   content: '';
   height: 5px;
   width: 0;
   left: 0;
   background: #b066ff;
   bottom: 0;
   transition: all 0.4s ease-out;
 }
 .list a:hover {
   cursor: pointer;
   color: #b066ff;
 }
 .list a:hover:after {
   width: 100%;
 }
 select {
   display: inline;
   border: 0;
   width: auto;
   margin-left: 10px;
   outline: none;
   -webkit-appearance: none;
   -moz-appearance: none;
   border-bottom: 2px solid #555;
   color: #7b00ff;
   transition: all 0.4s ease-in-out;
 }
 select:hover {
   cursor: pointer;
 }
 select option {
   border: 0;
   border-bottom: 1px solid #555;
   padding: 10px;
   -webkit-appearance: none;
   -moz-appearance: none;
 }
 .placeholder {
   border-bottom: 4px solid;
   cursor: pointer;
 }
 .placeholder:hover {
   color: #888;
 }
Enter fullscreen mode Exit fullscreen mode

JavaScript:

console.clear();


document.querySelector(".placeholder").onclick = function (e) {
  e.preventDefault();

  document.querySelector(".placeholder").style.opacity = "0.01";
  document.querySelector(".list__ul").style.display = "block";
};

document.querySelector(".list__ul a").addEventListener("click", function (ev) {
  ev.preventDefault();
  var index = document.querySelector(this).parent().index();
  document
    .querySelector(".placeholder")
    .text(document.querySelector(this).text())
    .css("opacity", "1");
  console.log(
    document.querySelector(".list__ul").querySelector("li").eq(index).html()
  );
  document
    .querySelector(".list__ul")
    .querySelector("li")
    .eq(index)
    .prependTo(".list__ul");
  document.querySelector(".list__ul").toggle();
});

  document.querySelectorAll(".list__ul a").forEach((q) => {
    q.addEventListener("click", function (ev) {
      ev.preventDefault();
      console.log(q.textContent);
      document.querySelector(".placeholder").textContent = q.textContent;
      document.querySelector(".placeholder").style.opacity = "1";
      document.querySelector(".list__ul").style.display = "none";
    });
  })
Enter fullscreen mode Exit fullscreen mode
<div>
  <div class="wrapper typo">The best browser is
    <div class="list"><span class="placeholder">FireFox </span>
      <ul class="list__ul">
        <li><a href="#"> Chrome</a></li>
        <li><a href="#">Brave </a></li>
        <li><a href="#">Chromium </a></li>
        <li><a href="#">Safari</a></li>
        <li><a href="#">Opera Mini</a></li>
        <li><a href="#">UC Browser</a></li>
      </ul>
    </div>

  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

We’ve seen some good examples of custom dropdown menus, but one thing we should keep in mind is the website’s accessibility.

What is web accessibility?

Web accessibility is a set of practices that entails designing and developing websites and digital tools so that people who are differently abled can use them without difficulty.

As web applications become more complex and dynamic, a new set of accessibility features and issues emerged. HTML introduced many semantic elements like < main > and < section >. Semantic HTML adds essential meaning to the web page rather than just presentation. This allows web browsers, search engines, screen readers, RSS readers, and users to understand it better.

W3C’s Web Accessibility Initiative — Accessible Rich Internet Applications is a series of specifications that define a set of new HTML attributes that can be added to elements to give additional semantics and improve accessibility where needed. The Web Content Accessibility Guidelines (WCAG) documents describe how to improve the accessibility of web content for individuals with impairments.

People with temporary disabilities, such as someone who has broken an arm, or situational limitations, such as when a person cannot listen to audio due to a lot of background noise, are also impacted by web accessibility.

Almost all websites now follow best practices, semantic HTML, and the proper HTML attributes. It is widely believed that making websites accessible to all users requires significant time and work while benefiting a relatively small number of individuals. However, this is not entirely correct. We all will face some kind of temporary disability at some point. Hence we need to consider everyone for accessibility.

To learn more about accessibility testing, you can watch the following video on performing accessibility testing with the Cypress test automation framework.

How to make dropdowns accessible?

To make it easy for people to find what they are looking for on your website, dropdown menus must be accessible. If not, it may take them longer to see what they need, or they may miss parts of your website entirely.

<!-- Bootstrap CSS Linked in Settings -->



<div class="container-fluid container-a">

  <div class="col-lg-6 col-lg-push-3 col-md-8 col-md-push-2 col-sm-10 col-sm-push-1 col-xs-12 content-card">

    <div class="title"><h1>A11Y Examples Series</h1></div>

    <h2>Basic Accessible Dropdown Menu</h2>

    <div class="dropdown-a dropdown">

      <button class="button-a dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown Menu</button>

      <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <li><a class="dropdown-item" href="#">Menu Item 1</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 2</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 3</a></li>
      </ul>

    </div>

    <br>

    <h2>Accessible Dropdown Menu w/ Headings</h2>

    <div class="dropdown-a dropdown">

      <button class="button-a dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown Menu</button>

      <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
        <li><h4 class="dropdown-header">Menu Header A</h4></li>
        <li><a class="dropdown-item" href="#">Menu Item 1a</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 2a</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 3a</a></li>
        <li><h4 class="dropdown-header">Menu Header B</h4></li>
        <li><a class="dropdown-item" href="#">Menu Item 1b</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 2b</a></li>
        <li><a class="dropdown-item" href="#">Menu Item 3b</a></li>
      </ul>

    </div>

  </div>
</div>






<!-- jQuery Linked in Settings  -->

<!-- Bootstrap js Linked in Settings -->
Enter fullscreen mode Exit fullscreen mode

The following are some of the best practices to keep in mind when dealing with dropdowns:

Good Semantics

A semantic element’s defining feature is that it conveys its meaning to both the developer and the browser. These elements define its content clearly. Whenever possible, use semantic HTML to make your menus accessible to screen readers and to make your code easier to understand.

  • Search engines and other user devices can use semantic HTML tags to determine the importance and context of web pages. Some of the HTML semantic tags are given below:

  • < article >: < article > tag is used to contain information that may be distributed independently from the rest of the site

  • < aside >: The < aside > element denotes a portion of a page that contains content that is indirectly linked to but distinct from the content around the aside element.

  • < figure >: The < figure > tag denotes self-contained information such as illustrations, diagrams, pictures, code listings, etc.

  • < nav >: The HTML element < nav > denotes a page part whose function is to give navigation links, either within the current content or to other publications.

  • < section >: A < section > is a semantic element used to create independent sections on a web page.

Structure the design

Structure the design so that everything is interconnected in some way so that the user has a roadmap for their journey. Structuring also entails placing headings, sections, navbar, headers, footers, etc., in the appropriate places. These semantic elements represent logical sections and provide a better way to structure the website.

A website with an accessible semantic structure, regardless of size or complexity, will be capable of providing accessibility. Without a solid semantic foundation, your website’s accessibility will degrade as it grows. Setting the proper structure early in development assists your website in remaining accessible as it grows.

image

  • Avoid keyboard pitfalls

    On websites, keyboard accessibility issues arise when designers or developers employ approaches that violate basic keyboard functionality. Problems occur when a user can navigate through a menu’s items using the Tab key but cannot leave the menu, leaving them in a loop.

    The following are some best practices for creating keyboard-accessible websites:

  • All links and controls can be accessed using the Tab key on the keyboard.

  • All the components in the UI should follow W3C’s WAI-ARIA practices.

  • Apps, plugins, widgets, and JavaScript techniques that trap the keyboard should be avoided.

  • Enhance the browser’s default focus indicator.

Implement a time delay between the mouse leaving the menu area and the menu closing. Visitors who can use a pointer but lack fine motor control require drop-down menus to be visible for a sufficient amount of time to be used. People should have a little bit of time to interact with the menu.

In the case of links as drop-down, the menu must be coded as an unordered list of links for assistive technologies used by blind users so that they can count the number of links in each drop-down menu or the main navigation. They also need to know which link takes them to the page they are currently on.

These are some of the most significant best practices for web accessibility. As we’ve seen, to make drop-down menus accessible, we need to consider the needs of different disabled user groups.

Creating the dropdown menu simple, straightforward, and understandable, giving them additional time to react to mouse movements, using the proper syntax for screen reader users, and ensuring your menus are compatible with the keyboard will eventually contribute toward better accessibility.

How to test custom menus on multiple browsers?

When creating a new menu for your website, how can you make sure that it is functional and works with all browsers? The answer is simple: Test the website on different browsers and operating system combinations.

However, the problem with testing your site’s custom menus on multiple browsers is that it can be time-consuming. You have to test every combination of operating systems and browsers, so you have to test your site on dozens or hundreds of combinations. This is a huge waste of time, especially when some combinations are irrelevant or superfluous.

There’s a good chance that there are significant differences between the way custom menus work in each browser, and you’ll need to test for these discrepancies. But rather than wasting all your time by going through the entire list of operating systems and browsers, you can use cloud testing tools like LambdaTest.

Cross browser testing platforms such as LambdaTest allow you to perform web testing and provide an online browser farm of more than 3000+ browsers and OS combinations.

Alternatively, you can use tools like LT Browser to check for responsive websites. LT Browser by LambdaTest is a mobile-friendly test tool with 50+ pre-installed viewports with multiple standard resolutions.

Subscribe to the LambdaTest YouTube channel for tutorials around Selenium testing, Playwright browser testing, Appium, and more.

Conclusion

Congratulations on reaching this far! You’re a fantastic reader!

In this detailed blog on creating custom Select menus with CSS, we have covered various ways to create the same with the help of HTML, CSS, and JavaScript. Not only did we experiment with creating dropdowns, but we also discussed various best practices and accessibility tips and tricks.

Now we know how to create your custom select menus most effectively and efficiently.

Happy Styling!

💖 💪 🙅 🚩
adarshm1024
AdarshM1024

Posted on March 28, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related