Styling HTML Combo Boxes
We should mention at the very outset that this technique is of limited practical utility since it relies on altering the opacity of the select element - pre IE7 this is not possible.
▼Luxembourg
The technique works thus
- We start with a fully transparent select element.
- Beneath it we place a suitably div.
- Within the div a span element floated to the right contains the ▼ character.
- We put in another span element to display the current selection in the combobox and assign its id attribute so it is available for modification through JavaScript.
- We attach JavaScript methods to the onmouseover and onmouseout events for the select element.
- We use these events to provide a measure of visual interactivity. This could be done in a variety of ways. Here we have simply chosen to alter the border-style style attribute of the div and span elements.
- Finally, we also code the onchange event in order to update the display when the user selects an option from the drop down list.
This technique works in Firefox, Opera and IE7 because the dropdown list shown by the select element is not transparent even though the actual element is. The skeleton code required to provide this functionality is shown below.
<html> <head> <script> function ButChange(AButs,AValue) { var i,e; for (i=0;i < AButs.length;i++) { e = document.getElementById(AButs[i]); e.style.borderStyle = AValue; } } function WhenChosen() { var e1 = document.getElementById("selcb"); var e2 = document.getElementById("selection"); e2.innerHTML = e1.options[e1.selectedIndex].value; } </script> <style> .cbCB,.cbD{position:absolute;background-color:#F2BA71;font-size:0.8em;height:1.5emtop:1.5em} .cbCB{opacity:0} .cbArr{float:right;background-color:#F2C99B;width:1em;height:1.2em;margin:0.1em;border:0.05em gray solid} </style> <!--[if lte IE 6]> <style>.cbD{display:none}</style> <![endif]--> </head> <body> <div class="cbD"id="seld"> <span class="cbArr" id="selarr" >▼</span><span id="selection">Luxembourg </span> </div> <select id="selcb" onchange="WhenChosen()" onmouseover="ButChange(['selcd','selarr'],'outset')" onmouseout="ButChange(['selcd','selarr'],'solid')"> <optgroup label="Europe"> <option>United Kingdom</option> <option selected="selected">Luxembourg</option> </optgroup> <optgroup label="Asia"> <option>India</option> <option>Dubai</option> </optgroup> </select> </body> <html>
- With some modification the technique can be made to work with relatively positioned elements.
- Note how the innerHTML property is being used to update the display.
- In practice, you will want to code additional actions in the onchange event.
- Note the use of IE Conditional Comments used to overcome the inability of pre IE7 versions to interpret the opacity setting for select elements.