How to set the background of the select depending on the selected element? For example, if you do this

#some-select option:first-child{ background-color: #FFEBFA; } 

This will change the background of the first item in the drop-down list. It is necessary to change the background of the select itself when selecting the first element.

  • Can you give me some example ... - MihailPw
  • @ AGS17 This is how it looks like joxi.ru/vAWp1jLCJE6ErW , if any of the elements is selected. I would like, with the selected "1", to change the background / font - cruim
  • As far as I know, you can't do without JS here - MihailPw

1 answer 1

At the moment with the help of css it can not be done, but in the future the pseudo-class will be available : has () , which you can use according to the idea:

 select:has(> .red:checked) { background: red; } 

Which means, if the select element is the parent of the selected element with the red class (in your case option), then we describe the styles for it.

https://drafts.csswg.org/selectors-4/#relational

Using jquery, you can do it like this:

 $('.select').change(function() { var selectedColor = $('.select option:selected').val(); $('.select').css('background', selectedColor); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="select"> <option selected="selected" value="--">--</option> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> <option value="grey">grey</option> </select> 

  • there is a selection in the drop-down list itself, and I need to change the background color on the selection itself - cruim
  • @cruim, the answer is changed, now it is the background select'a that is changing - Gleb Ostrikov