I have a drop down box on a web page, using the HTML5 <select>
tag. There are times where I want to make it "read only", that is display it as text only. For example:
Sometimes I want it to be "read/write":
And other times I want it to be "read only":
I would prefer not to use the "disable" attribute. I think it looks tacky, and implies that there is somehow a choice to the user when none is available.
Is it possible to transform the look of the current option for a select
into normal text using CSS?
<select> tags can be styled through CSS just like any other HTML element on an HTML page rendered in a browser. Below is an (overly simple) example that will position a select element on the page and render the text of the options in blue.
You can use inline styles to add custome styling to <option> tags. For eg : <option style="font-weight:bold;color:#09C;">Option 1</option> This will apply the styles to this particular <option> element only.
To change the selected option in an HTML <select> element we have to change the value property on the <select> element or the selected property on the <option> element we want to get selected.
To do so, we change the visibility of this text using CSS to hidden first. Then we add a new text at the exact same position, using the pseudo elements and corresponding explicit positioning. Note that after is the pseudo element in use here. We use the visibility modifier once again to show the new text.
Yes, use the CSS:
select {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
border: none;
/* needed for Firefox: */
overflow:hidden;
width: 120%;
}
example:
http://jsfiddle.net/eG3dS/
Because of the "needed for Firefox" section, you will need to make a div or span that constrains the select box size. It's too bad FF doesn't respect moz-appearance
here.
Note that even though this makes it look like normal text, it is still a working select box! You will need to disable it some way, either by using the "disabled" attribute and changing the font color or otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With