Styling drop-downs

country-dropdown

Here’s how to style the options for a select drop-down. It uses some javaScript to add a class to the select options to match each option, and to add the selected option’s class to the select element itself.

The CSS:

.store-countries {
    padding-left: 20px;
    background-position: 4px 2px;
    background-repeat: no-repeat;
}
.store-countries option {
    padding: 0 0 0 24px;
    background-position: 2px 4px;
    background-repeat: no-repeat;
}
.store-countries option.Belgium {
    background-image: url(../images/icons/flags/be.gif);
}
.store-countries option.France {
    background-image: url(../images/icons/flags/fr.gif);
}
.store-countries option.Germany {
    background-image: url(../images/icons/flags/de.gif);
}

The jQueries:

function dropDownCountries() {
    $('.store-countries').find('option').each(function() {
        var country = $j(this).val();
        $(this).addClass(country);
    });
    
    var selectedFlag = $('.store-countries').find('option:selected').css('background-image');
    $('.store-countries').css('background-image',selectedFlag)
        
    $('.store-countries').change( function() {
        var selectedFlag = $('.store-countries').find('option:selected').css('background-image');
        $('.store-countries').css('background-image',selectedFlag)
    });
}

2 Responses to Styling drop-downs

View the comments
  1. What if one of the options has more than one word – e.g. United Kingdom?

Add a comment

Leave a Comment

Your email address will not be published.