cwd cwd - 6 months ago 26
HTML Question

How can I use the CSS pseudo-element :before{ content: '' } to affect an <option> element?

If I have a list of optons, how can I use the CSS pseudo-element :before{ content: '' } to affect the

<option>
? Below there are three options an I'd like to insert text before each one.

I know this can be done wit javascript / jQuery, but is it possible with CSS?

<html>
<head>
<style>

option::before {
content: "sandy - "
}

</style>


</head>
<body>

<select>
<option>beach</option>
<option>field</option>
<option>carpet</option>
</select>


</body>
</html>

Answer

The ::before and ::after pseudo-elements actually prepend/append a child node to the element, so this will not work on any element that cannot contain child nodes.

It would be (roughly) the equivalent of doing:

<option><span>sandy - </span>beach</option>

If you want to update the text value, you will need to use JavaScript.