Set selected option via CSS?

14,247

Solution 1

Nope, CSS only alters the presentation, not the content (although CSS3 does support some modification of content, but not the selection of values.) You'll need to use JavaScript if you can't modify the HTML directly.

Solution 2

option[selected] {background-color:skyblue;color:white;}

in case you want to show the previous marked selection - independend of the changes from the user after displaying a result, the old selected remain sykblue, the new changes are in darkblue.

Solution 3

Not via CSS, but it can be accomplished via javascript.

function setSelects() {

    var allSelects = document.getElementsByTagName("select");
    for (var i = 0; i < allSelects.length; i++) {
        for (var j = 0; j < allSelects[i].options.length; j++) {
            if (allSelects[i].options[j].className == "selected") {

                allSelects[i].selectedIndex = j;
            }
        }
    }
}

window.onload = setSelects;

As other people have pointed out, I'm not sure why you'd want to do it via a CSS class in the first place.

Solution 4

If you use JQuery then you can do something very much along those lines, but not CSS on its own.

Solution 5

Yes it is possible, but I am not sure about IE

Below code will change style for default selected item.

           <style>
           option[selected="selected"] {
           color:red;
           font-weight:bold
           }
           </style>

           <select>
           <option value="1">Txt</option>
           <option value="2" selected="selected">Another Txt</option>
           </select>
Share:
14,247
Travis Beale
Author by

Travis Beale

NADA

Updated on June 04, 2022

Comments

  • Travis Beale
    Travis Beale almost 2 years

    Is it possible to set the selected attribute of an option tag via a CSS class?

    I'm wondering if something like the following is possible in a stylesheet:

    option.selected {
      selected: true;
    }
    

    Then in HTML:

    <option class="selected">
    

    Which would have the same effect as setting the selected attribute. Is this technique possible?