Giving a colour to multi-select at initialization

Hi all,

Two topics on top of each other is going to look desperate, but my efforts have been mostly unfruitful due to my inexperience. I’d greatly welcome your help.

Many thanks to kevin-brown (over at GitHub, can’t find his username here) whose jsfiddle I forked, I have a jsfiddle somewhat similar to my code. Here it is: https://jsfiddle.net/qhnksgud/ .

My question: How do I make the multi-select accept colour at initialization rather clicking on it to have it be coloured?

Thanks for your time!

James

I’m not quite sure what you mean by “accept color”, but I’m guessing—based on the behavior of the fiddle you provided—that you want the “box” that displays the items the user has selected to be red. If that’s correct, this bit of CSS will do it for you:

.select2-selection.select2-selection--multiple {
  background: red;
}

That will change the color for every compoment in the page. What if I have several components and I want a different color for each of them? How is it possible to define the background color of selections at the initizalization of the component?

Best,
Tino

In that case, you will need to give each of your HTML select elements its own unique id attribute value. For example: <select id="my-select-1" multiple>, <select id="my-select-2" multiple>, and so on. Then, you will be able to target each of the Select2 input areas with CSS like the following:

#my-select-1 + .select2.select2-container .select2-selection.select2-selection--multiple {
  background: red;
}
#my-select-2 + .select2.select2-container .select2-selection.select2-selection--multiple {
  background: blue;
}

You could also use classes to control the color you assign to each Select2. For instance:

<select class="select2-multiple select2-red" multiple>
...
</select>
...
<select class="select2-multiple select2-blue" multiple>
...
</select>

and then your CSS would be:

.select2-red + .select2.select2-container .select2-selection.select2-selection--multiple {
  background: red;
}
.select2-blue + .select2.select2-container .select2-selection.select2-selection--multiple {
  background: blue;
}

This works! But what if I want to change the background color of the selected choices and not the background color of the whole component?

I cannot find the rationale on how the css are addressed…

Ok, I achieved it by doing:

.select2-red + .select2.select2-container .select2-selection__choice{
  background-color: red;
}

Thanks!

1 Like