You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Select2下拉框的每个选项设置不同颜色?

How to Color Select2 Dropdown Panel Options

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:52:19