Cypho
Cypho

Reputation: 103

CSS Element and Text opacity

Is there any option to set opacity of the element, in my case its drop down menu, to zero but the text opacity in this element to 100 ? I want to do that because with 0 opacity I can hide the arrow but the text hides too, so I need a workaroound

Upvotes: 1

Views: 257

Answers (2)

xec
xec

Reputation: 18024

No, opacity applies to the whole element (including descendants). You can, however, use colors with transparency for the background (assuming it is a solid color)

div {
    background-color: rgba(0, 0, 0, 0.5); /* black with 50% opacity */
    color: black; /* text is black with 100% opacity */
}

Demo at http://jsfiddle.net/ESzTT/1/

EDIT

Like Zachary Kniebel states in his answer, this will not work for <select> and <option> elements. You can have dropdown menus with other elements, or if this is for a form field, there are javascript libraries that replace the DOM elements in order to make them stylable.

Upvotes: 0

Zachary Kniebel
Zachary Kniebel

Reputation: 4774

No, there is no way to do this, because the children inherit the opacity property from the parent (this cannot be changed), and <option> elements cannot exist outside of the <select> element.

In other words, if you set the <select> element's opacity to 0, you are effectively hiding the element and its children.

Were you not using a <select> element, I would say that you could use position: relative; or position: absolute with a z-index to overlay your text over the parent element whose opacity has been set to zero.

I do remember researching this issue, myself, when I first started diving into the wonderful world of web development. This situation is a perfect example of how w3schools gives bad information, as their example makes it look like this can be done.


If you really need a solution for this, then I would advise that you do what we all love to do, when an existing tool isn't present: invent one. Make your own version of the <select> element, and use JavaScript to make it work. You can even make your own XML tag and use JavaScript to tell it how to render and act. Alternatively, you could just use <div>s, <span>s (and others, of course), along with CSS and JavaScript to make this happen.

Good luck! :)

Upvotes: 2

Related Questions