GreenTriangle
GreenTriangle

Reputation: 2460

How is it possible to style the selected element within a select element?

I have a select element with multiple options inside. I also have a text input with a datalist full of options.

What's maddening is that if I style option { font-size: 14pt }, it styles all the options in the select dropdown, but none of the options within the input type='text' dropdown. They're all option elements, and I can't find in my books or on Google why this style would only apply to some of them.

Nor does it style the selected option. When it's in the dropdown list, it's styled. But if it's sitting as the currently-selected element, it isn't. Again, it's always an option element, so why would the style not apply to it everywhere?

Upvotes: 3

Views: 48

Answers (2)

tkiddle
tkiddle

Reputation: 480

It is not possible to do what you are trying to achieve. You can, to a certain extent style the select box but not the options.

To style the select box you'll need to remove the default styling using the appearance property and then apply your css:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
   background: red;
   font-size: 16px;
}

If you really need to style options you have to create a faux select element with other html elements. e.g. a list with list items instead of options:

<ul>
  <li></li>
</ul>

The same applies for the data list.

Not using default form elements (i.e. creating faux elements) just to fit in with design can have impacts on accessibility. It's always best to weight up the pros and cons.

If accessibility isn't a concern go for gold!

Upvotes: 1

Steve Harris
Steve Harris

Reputation: 5109

It is not possible. I don't use select elements at all. You can instead use a readonly input textbox for display and a <ul> list that is hidden until the textbox is focussed where each <li> updates the value of the textbox on click.

Upvotes: 1

Related Questions