Date: 2014feb26
Product: web
Q. How can I color alternating options in an html select?
A.
THE MODERN WAY - WORKS FOR CURRENT BROWSERS
<style>
option:nth-child(even) {background: #ccc }
option:nth-child(odd) {background: #eee }
</style>
<select name=myselect>
<option>Stuff</option>
<option>Stuff</option>
<option>Stuff</option>
<option>Stuff</option>
<option>Stuff</option>
<option>Stuff</option>
<option>Stuff</option>
</select>
THE OLD WAY - WORKS FOR EVERY BROWSER
Make a style class called "odd", use jQuery to apply it.
<!-- define the "odd" style -->
<style>
.odd { background-color: #eee; }
</style>
<!-- load jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<!-- Use jQuery to apply the style -->
<script>
$(document).ready(function() {
$("option:odd").addClass("odd");
});
</script>
<!-- The <select> with some <option>s -->
<select name=myselect>
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>