Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Centre text in OPTION tag

Status
Not open for further replies.

jawa500

Programmer
Dec 18, 2002
8
EU
I am trying to centre text in an OPTION list.

I can get the following sample code to work in Firefox but IE still left justifies the text.

Code:
<SELECT>
<OPTION value="" selected>Select Letter A-C
<OPTION style="TEXT-ALIGN: center" value=A>A
<OPTION style="TEXT-ALIGN: center" value=B>B
<OPTION style="TEXT-ALIGN: center" value=C>C
</SELECT>

Any suggestions for a work around?

------------------------------------------
the only shopping site you need to bookmark
 
You asked for a work-around. If the user has JavaScript enabled, then you can create a function which cycles through the text of each drop-down option, figures out which is the longest one, and changes the text of each accordingly (adding spaces to the front and back of each). You will need to enforce use of a mono-space font for this, however.

Here's an example:
Code:
<html>
<head>
<script>
function centerSelect()
{
 var df = document.forms[0];
 var longest = "";

 [red]//find longest text in drop-down[/red]
 for (var i=0; i<df.mySelect.options.length; i++)
 {
  var temp = df.mySelect.options[i].text;
  if(temp.length > longest.length)
   longest = temp;
 }//end for

 var longLength = longest.length;

 [red//update text of each option in drop-down[/red]
 for(var i=0; i<df.mySelect.options.length; i++)
 {
  var optLength = df.mySelect.options[i].text.length;
  var toAdd = longLength - optLength;
  if(toAdd%2 == 1)
   toAdd += 1; [red]//just so later div-by-2 easy[/red]

  var temp = " "; [red]//starts with one space to compensate for drop-arrow on right[/red]
  for(var j=0; j<toAdd/2; j++)
   temp += " ";

  temp += df.mySelect.options[i].text;

  for(var j=0; j<toAdd/2; j++)
   temp += " ";

  df.mySelect.options[i].text = temp;
 }//end for
}//end function
</script>
</head>
<body [red]onload='centerSelect();'[/red]>
<form>
<select name='mySelect' [red]style='font-family:Courier New'[/red]>
<option>one</option>
<option>thirteen</option>
<option>twenty-one</option>
</select>
</form>
</body>
</html>

Eh.

--Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top