No, it is not possible to make a <select>
list drop down on hover using only HTML and CSS. The behavior of the <select>
element is controlled by the user’s browser and cannot be altered using only HTML and CSS.
However, you can simulate a dropdown menu using CSS and JavaScript. One approach is to hide the <select>
element using CSS and create a custom dropdown menu using HTML, CSS, and JavaScript. When the user clicks on the custom dropdown menu, the JavaScript code can simulate the behavior of the <select>
element and update its value.
Here’s an example of how you can create a custom dropdown menu using HTML, CSS, and JavaScript:
html
<div class="custom-select">
<select id="my-select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</div>
css
.custom-select {
position: relative;
display: inline-block;
}
.custom-select select {
display: none;
}
.custom-select .select-menu {
position: absolute;
top: 100%;
left: 0;
right: 0;
z-index: 1;
display: none;
}
.custom-select:hover .select-menu {
display: block;
}
javascript
const select = document.getElementById('my-select');
const selectMenu = document.createElement('div');
selectMenu.className = 'select-menu';
selectMenu.innerHTML = `
<div class="select-option" data-value="option1">Option 1</div>
<div class="select-option" data-value="option2">Option 2</div>
<div class="select-option" data-value="option3">Option 3</div>
`;
select.parentNode.insertBefore(selectMenu, select.nextSibling);
select.addEventListener('change', function() {
const selectedOption = select.options[select.selectedIndex];
const selectedValue = selectedOption.value;
const selectedText = selectedOption.textContent;
selectMenu.querySelector(`[data-value="${selectedValue}"]`).classList.add('selected');
selectMenu.querySelectorAll('.select-option:not([data-value="' + selectedValue + '"])').forEach(function(option) {
option.classList.remove('selected');
});
});
selectMenu.querySelectorAll('.select-option').forEach(function(option) {
option.addEventListener('click', function() {
const value = option.getAttribute('data-value');
select.value = value;
select.dispatchEvent(new Event('change'));
});
});
In this example, we are hiding the <select>
element using CSS and creating a custom dropdown menu using a <div>
element with the class .select-menu
. We are then using JavaScript to simulate the behavior of the <select>
element when the user interacts with the custom dropdown menu. When the user clicks on an option in the custom dropdown menu, the JavaScript code updates the value of the <select>
element and triggers a change event.