I'm using a select2 dropdown, and would like to set different colours on each options.
Example:
<select class="select2" name="fruit">
<option class="red-option">Apple</option>
<option class="green-option">Kiwi</option>
<option class="blue-option">Grape</option>
</select>
I can colourize the rendered, selected option as follow:
.select2-selection__rendered[title="Apple"] {
color: red !important;
}
How to also colourize the options in the select2 dropdown - either based on the option class ('red-option') or value ('Apple')?
PS: I use bootstrap 3.3 + jQuery and don't mind using JS to do this if I must.
Got it.
Select2 generates an id attribute for all the dropdown options, using the parent select
's name
attribute.
With my example, I was able to apply a colour using :nth-child(x) as follow:
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(1) {
color: red;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(2) {
color: green;
}
.select2-results__options[id*="select2-fruits"] .select2-results__option:nth-child(3) {
color: blue;
}
<select class="select2" name="fruit">
<option class="red-option">Apple</option>
<option class="green-option">Kiwi</option>
<option class="blue-option">Grape</option>
</select>