Alex Rivera | Logout

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

Asked 2012-07-02T12:16:36.997
15

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 wel</div>
                    
                    <div class= html whitespace html-select

Edit
Report

1 Answer

17

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.

answered 2012-07-02T12:28:11.997

Your Answer