如何为Select2下拉框的每个选项设置不同颜色?
Nice start with styling the selected option! To add colors to the dropdown panel options too, you have a couple of solid approaches depending on your needs:
Approach 1: CSS Only (Quick & Simple)
Select2 renders dropdown options inside the .select2-results__option class. You can target these using the :contains() pseudo-class to match the option text, just like you did for the selected state:
/* Your existing code for the selected option */ .select2-selection__rendered[title="Apple"] { color: red !important; } .select2-selection__rendered[title="Kiwi"] { color: green !important; } .select2-selection__rendered[title="Grape"] { color: blue !important; } /* Style dropdown panel options */ .select2-results__option:contains("Apple") { color: red !important; } .select2-results__option:contains("Kiwi") { color: green !important; } .select2-results__option:contains("Grape") { color: blue !important; }
Note: The :contains() selector is case-sensitive, so make sure the text matches exactly what's in your <option> tags.
Approach 2: Custom Rendering with JavaScript (More Robust)
If you want a solution that doesn't depend on option text (e.g., if text might change dynamically), use Select2's templateResult option to inherit the original option's CSS classes. This way, you can define styles once and apply them to both the selected state and dropdown options:
First, update your Select2 initialization code:
$('.select2').select2({ templateResult: function(option) { // Skip rendering for placeholder options (if you use one) if (!option.id) { return option.text; } // Create a span element with the original option's class const $optionElement = $('<span>').addClass(option.element.className).text(option.text); return $optionElement; } });
Then simplify your CSS to target the classes directly (this replaces your existing selected-state CSS):
.red-option { color: red !important; } .green-option { color: green !important; } .blue-option { color: blue !important; }
This works because both the rendered selected item and dropdown options will include the original <option>'s class, so the styles apply everywhere consistently.
内容的提问来源于stack exchange,提问作者foob.ar

