Home >Web Front-end >CSS Tutorial >How Can I Change the Background Color of a Selected
Option in HTML? " />
CSS Styling for HTML <select> Selected Option Background Color
In HTML, the <select> element is used to create drop-down lists for user selection. By default, when an option is selected, its background color turns blue. However, you may desire to customize this color using CSS.
The CSS property "selected-color" does not exist for styling the background color of a selected <select> option. Pure CSS alone may not suffice for this task.
Javascript Solution
A more feasible approach involves using a combination of HTML, CSS, and Javascript to achieve the desired result. Here's how:
<select>
In the above HTML code, we have created a <select> element with a predefined red background color.
select { color: black; /* Default color for options */ }
This CSS sets the default color of all
var sel = document.getElementById('mySelect'); sel.addEventListener('click', function(el){ var options = this.children; for(var i=0; i < this.childElementCount; i++){ options[i].style.color = 'white'; } var selected = this.children[this.selectedIndex]; selected.style.color = 'red'; }, false);
In this Javascript code, we add an event listener to the <select> element. When an option is clicked, it loops through all the
By combining HTML, CSS, and Javascript, you can override the default blue background color of selected <select> options and customize it to your liking.
The above is the detailed content of How Can I Change the Background Color of a Selected