Make part of a <select> dropdown input option underlined with CSS

Viewed 171

I'm attempting to underline part of the text in an input field only using CSS.

I can underline the entire option by adding the text-decoration: underline to the select element like so:

.underline {
  text-decoration: underline;
}
<select name="id" id="products" class="underline">
  <option value="val1">my value 1</option>
  <option value="val2">my value 2</option>
  <option value="val3">my value 3</option>
</select>

I tried wrapping a span tag on the innerText of the option element text I'm interested in and adding the same class to the span element..

<select name="id" id="products">
  <option value="val1">my <span class="underline">value 1</span></option>
  <option value="val2">my <span class="underline">value 2</span></option>
  <option value="val3">my <span class="underline">value 3</span></option>
</select>

.. but this doesn't have the desired effect as it seems you can't style option elements.

Is there a way to achieve this without using Javascript?

1 Answers

Unfortunately, as of 2022, I do not believe this is possible. If we look at the [MDN reference page for the <option/> element, we see that the "permitted content" section notes that an option is allowed to contain:

Text, possibly with escaped characters (like &eacute;).

As such, MDN's reference implies that inclusion of any HTML elements such as a <span/> would be disallowed by the spec. This is most likely why browsers do not style it as you would expect-- from the browser's perspective, it doesn't expect any such content because it is forbidden.

The only way I could see this being perhaps possible without JS would be if you could find sufficient unicode characters to use in place of the plain characters using some online tool like Yay Text Unicode Underline-- with this tool I was able to get "Value 3" underlined in a few different styles, like:

v̲a̲l̲u̲e̲ ̲3̲

Obviously, this is solution is far from ideal-- it is not certain to work or be have wide browser compatibility, and I suspect it would be a difficult development undertaking.

Most likely, if this is a critical requirement, you'll have to look at creating a similar component using HTML, CSS, and JS. If you take this route, I recommend you use an online example from the W3 showing how to create an accessible component, such as this collapsible listbox example-- this way you can be certain that your resulting UI is appropriately accessible to those using keyboards, screen readers, or other assistive technologies.

Related