MAX POWER
MAX POWER

Reputation: 5448

CSS - change font-family for individual select options

Here is what I am trying to acheive:

I have got this working to the above requirements in Firefox and IE11 but not in Chrome 36 (Windows).

Here is a JSFiddle: http://jsfiddle.net/KhvJc/

CSS:

select {
    width: 150px;
    font-size: 12px;
    padding: 5px;
    height: 30px;
}

/* when the first option is selected */
select.empty {
    color: #959595;
    font-family: Verdana;
}

/* all options except the first when the first option is selected and the select has focus */
select.empty:focus option:not(:first-child) {
    color: #282525;
    font-family: Arial;
}

/* first option when the select has focus */
select:focus option:first-child {
    color: #BDBDBD;
    font-family: Verdana;
}

JS:

$('select').change(function(){
    if($(this).val() == '')
    {
        $(this).addClass('empty');
    }
    else
    {
        $(this).removeClass('empty');
    }
}).change();

HTML:

<select>
    <option value="">Empty Option</option>
    <option value="1">Option 1</option>
    <option value="1">Option 2</option>
    <option value="1">Option 3</option>
    <option value="1">Option 4</option>
</select>

As you will see, in Chrome it does not apply the font-family to individual options but it does manage to apply the color. Anybody know how to fix this?

Upvotes: 3

Views: 3755

Answers (3)

frogatto
frogatto

Reputation: 29285

Try this : (I've tested it in my Firefox and works fine)

/* For non-first options */
.not-first {
    color: #282525;
    font-family: Arial;
}

/* For first option */
.first {
    color: #BDBDBD;
    font-family: 'Times New Roman';
}

JavaScript codes:

$('option')
    .first().addClass('first')
    .siblings().addClass('not-first');

$('select').change(function(){
    $(this).attr('class', $('option:selected', this).attr('class'));
}).change();

JSFiddle

Upvotes: 4

Vamshi
Vamshi

Reputation: 41

Add !important to the attribute values.

Upvotes: -1

guest271314
guest271314

Reputation: 1

Not certain about exact sequence of logic at OP ? Is option:first-child the only element whose font-family property is intended to be set to Verdana ? With other option elements font-family property set to Arial ? Then , after initial select , or change event , option:first-child font-family is set to Arial ?

The piece at OP appear to work o.k. at jsfiddle , setting font-family , at chrome unstable (37) , and chromium (33).

If not appear to work there , try adding

!important

after font-family property value, i.e.g.,

Verdana !important;

Arial !important;

jsfiddle http://jsfiddle.net/guest271314/kAdL9/

jsfiddle http://jsfiddle.net/guest271314/E2dze/ (applying Monospace and Impact fonts , respectively ; which may be easier to view the differences of ?)

See

Override USER AGENT STYLE SHEET - Chrome

chrome : how to turn off user agent stylesheet settings?

Upvotes: 4

Related Questions