htshame
htshame

Reputation: 7330

Change color of selected multiselect items

I have a multiple select element on the page:

<select multiple="multiple">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
</select>

Its options color is black. But when I select an option, its color becomes white.

How can I change color of selected option to black (or some other color I want) with css?

I tried using

but they don't do the trick.

UPD: here is the jsfiddle of what I need: https://jsfiddle.net/htshame/th3gesvv/4/

Upvotes: 0

Views: 6452

Answers (1)

Ala Eddine JEBALI
Ala Eddine JEBALI

Reputation: 7841

I don't know how to achieve this only in CSS but I know that you can select the selected option using CSS.

My suggestion is to use jQuery to update the attribute of the selected option and then change the CSS rule [selected] to put your preferred background color.

Here is a running example:

$(document).ready(function() {
$('select').change(function() {
   var selectedOption = $(this).find(':selected');
   selectedOption.attr('selected','selected');
}).change();
});
select{height: 200px; width: 300px;}
option {margin: 10px;}

[selected] {
    background-color: #0f0;
    font-weight:bold;
}
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<select multiple="multiple">
  <option>One</option>
  <option>Two</option>
  <option>Three</option>
  <option>Four</option>
  <option>Five</option>
</select>

Upvotes: 2

Related Questions