0

I am trying to customise my tags in my HTML form. I want each option in my select input to have a different background colour. I started off using this link then tried to change it but it then disappeared altogether. I know HTML, CSS and a bit of JS. My select menu has different colours and each colour should option should have that colour background. eg the 'Red' option will have a red background with white text etc.

Here is my code:

<select>
    <option style="background-color: #fff;" value="0">Select colour:</option>
    <option style="background-color: #00f;" value="1">Blue</option>
    <option style="background-color: #fff;" value="2">White</option>
    <option style="background-color: #f40;" value="3">Orange</option>
    <option style="background-color: #0f0;" value="4">Green</option>
</select>

However this has no effect whatsoever. I want to do this all while using as few as languages as possible. Any ideas whether this is possible? Thanks

  • You can not style `select` or `option` elements cross-browser. Your only real option is to replace the select element entirely with other HTML elements that _can_ be styled (div, ul, li etc) – Turnip Dec 12 '19 at 14:21

2 Answers2

0

The easiest way to do this would be to give each option a seperate ID like so <option id="red"></option>. Then In the <head> </head> of your page you would then type something like this:

<style>

#red { 
background-color: red;
}

#green{ 
background-color: green;
}

#yellow{ 
background-color: yellow;
}

</style>

If this isn't wat you meant please comment!

T B Duzijn
  • 21
  • 10
0

Since you want to use as few languages as possible, here are two approches using only HTML & CSS :

Data attributes or classes

While the solution provided by T B Duzijn would work, I believe that using something like data-bg-color="red" or class="bg-color-red" would be better than id="red", because it would be reusable later (id should always be an unique identifier in the entire document)

HTML :

<option data-bg-color="blue" value="1">Blue</option>

CSS :

option[data-bg-color="blue"] {
   background: blue;
}

CSS custom properties

Depending on the browsers you want to support (Support is pretty good, including Edge, but no IE) you could also use custom properties like this :

<option style="--mycolor:blue;" value="1">Blue</option>

And then in CSS :

option {
  background: var(--mycolor);
}

Which highly reduces repetitions of the same CSS rules for different colors.

weirty
  • 1