mArtinko5MB
mArtinko5MB

Reputation: 788

How to change color of selection in Select2 4.0.1?

Hello i'm trying to figure out how to change the color of the selection (only if selected by user, placeholder has to be in default color - white) with select2 4.0.1

this is how it should look like in default, 3rd pic (first two are selected) enter image description here

and after selection it should look like : enter image description here

I know how to set CSS for select2 3.5.x but recently we've decided to update our select 2 and i'm struggling ...

original CSS for select2

.select2-container .select2-choice:not(.select2-default) {
background-image: none;
background-color: #D9FFC7;}

anyone? thanks for reply

working jsfiddle

Upvotes: 1

Views: 9126

Answers (1)

Ash Thornton
Ash Thornton

Reputation: 140

Looks like you just have to add an !important to the background-image property, or make sure your custom CSS is included in your page after you include the select2 CSS.

.select2-container .select2-choice:not(.select2-default) {
    background-image: none !important;
    background-color: #D9FFC7;
}

UPDATE

Ok, looks like your JSFiddle was using the previous version of select2 when I was editing it. Now I see your problem.

Trying to stick with a pure CSS solution, I have come up with this:

.select2-selection {
    overflow: hidden;
}

.select2-selection__rendered[title] {
    background-color: #D9FFC7;
}

This will target the element that updates when you make a selection - a title attribute gets added to the .select2-selection__rendered element when you choose an option from the dropdown, so the above CSS will change the background colour when there is a title attribute present.

The overflow: hidden property is in there because when you change the background colour of that element, it spills out of the parent's element.

The flaw in this set up is that if you clear the selection, the title attribute stays there with the last option you had selected, meaning the field is left with the background coloured.

Upvotes: 3

Related Questions