Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve whitespace in HTML select element options using "white-space: pre" NOT working

My problem comes from HTML dropdown select not able to preserve multiple consecutive whitespaces in its options. Here is a sample testcase and outcome.

The "white-space:pre" class CSS seems to work only for any HTML element except the select element options. Is there any literature or cases identifying such issue?

print "<style>.keepwhitespace { white-space: pre }</style>
<p class='keepwhitespace'>abc   def</p>
abc   def
<br/>
<br/>select and options with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\" class='keepwhitespace'>
<option class='keepwhitespace'>Any </option>
<option class='keepwhitespace'>abc   def </option>
<option class='keepwhitespace'> Any  </option>
<option class='keepwhitespace'>abc def </option>
</select>
<br/>select with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\" class='keepwhitespace'>
<option >Any </option>
<option >abc   def </option>
<option> Any  </option>
<option>abc def </option>
</select>
<br/>options with keepwhitespace
<select onchange=\"alert('\''+this.value+'\' '+this.value.length)\">
<option class='keepwhitespace'>Any </option>
<option class='keepwhitespace'>abc   def </option>
<option class='keepwhitespace'> Any  </option>
<option class='keepwhitespace'>abc def </option>
</select>";

Outcome looks like this:

preloaded As can be seen in the "p" element tag (and any other that I tried using, worked well formatting text with the "whitespace" CSS style. Yet the select does not.

As can be seen in the "p" element tag (and any other that I tried using, worked well formatting text with the "whitespace" CSS style. Yet the select does not.

on selection to view the item value string and length of string (the length SHOULD have been 10 instead of 7, 'abc def' is 8 chars in length)

on selection to view the item value string and length of string (the length SHOULD have been 10 instead of 7, 'abc  def' is 8 chars in length)

like image 385
luhfluh Avatar asked Jul 02 '12 12:07

luhfluh


1 Answers

Form inputs usually map to their relevant native OS controls so they can be hard to style. The usual workaround to keep whitespace from collapsing into 1 space in <option>s is to use &nbsp; instead of usual spaces.

eg. one of your options would be:

<option>&nbsp;Any&nbsp;&nbsp;</option>

For more custom appearance, you would hide the real select element completely and replace it with custom markup and javascript.

like image 66
Teoulas Avatar answered Sep 22 '22 14:09

Teoulas