How do I create a multiple-selection dropdown menu using checkboxes in HTML and CSS?

Susan Sarandon
Release: 2024-11-11 08:37:03
Original
1061 people have browsed it

How do I create a multiple-selection dropdown menu using checkboxes in HTML and CSS?

How to Integrate Checkboxes into a Dropdown Menu

Creating a multiple-selection dropdown list allows users to select multiple options conveniently. Although you might be tempted to use a simple checkbox in front of the dropdown field, this method displays the checkbox for the entire list instead of for each option. To achieve the desired functionality, follow these steps:

Creating a Dropdown Checklist:

Consider the following HTML and CSS code to create a simple dropdown checklist:

<div>
Copy after login
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
Copy after login

JavaScript can be used to control the visibility of the checkbox list.

var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
};
Copy after login

Result:

This solution creates a dropdown menu where you can select multiple options by checking the checkboxes. The "anchor" element acts as a button to open and close the checkbox list. Styling can be customized as needed to match your website's design.

The above is the detailed content of How do I create a multiple-selection dropdown menu using checkboxes in HTML and CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template