Explain Codes LogoExplain Codes Logo

Css :selected pseudo class similar to :checked, but for `` elements

html
responsive-design
css
styling
Anton ShumikhinbyAnton Shumikhin·Feb 4, 2025
TLDR

In order to style <option> elements when selected, some JavaScript skill is needed since CSS lacks a :selected pseudo-class. Use the change event on the <select> to trigger a style change. Here's a concise approach:

document.querySelector('select').addEventListener('change', function() { this.className = this.value ? 'selected' : ''; });

Next, inject some life into our <select> using CSS:

select.selected option:checked { background-color: yellow; /* Who doesn't love yellow, it's like sunshine without the sunburn */ }

Deep Dive: Enhancing Option Styles

Now, let's take a deeper dive into how we're going to style these cheeky <option> elements.

The Styler's Toolkit: Direct <option> styling

Styling <option> elements can be a bit like herding cats due to differences between browsers. However, just as with cats, some tactics are often reliable, such as styling the color and background color properties.

For a "notice-me" style with the selected <option>, try:

option:checked { color: red; /* Sure to grab attention faster than a squirrel at a dog convention */ }

To hide the selected item when the dropdown is closed, you can give this a whirl:

select:not(:focus) option:checked { display: none; // Hide-and-seek champion, unlimited times }

Although this may behave similar to a chameleon, blending in with all browsers as HTML rendering differences exists.

Shine that Spotlight: Styling the Closed Dropdown

To make our closed <select> element shine like the star it is, based on the current selection:

select { color: red; // Turns out, red is the new black! } select option:not(:checked) { color: black; }

Looking Fancy with Gradients

Enter the realm of linear-gradient as a background-image for a subtle gradient effect on your <option> elements:

option:checked { background-image: linear-gradient(to right, #ffe0e0, #ffd6d6); /* For when 50 shades of red isn't enough */ }

Remember, Gecko/webkit browsers like Firefox and Chrome are like your quirky friends who are more accepting of funky gradients on <option> elements.

Adapting Styling Techniques for <option>

One Does Not Simply Use Inline Styles on <option>

To ensure smooth cloning of cross-browser consistency, we often prefer to use the style attribute directly on the <option>:

<option style="color: red;" selected>Chosen option</option>

Finders Keepers: Targeting with Attributes

Identify a specific <option> by its selected attribute and style it like it's the star of the show:

option[selected] { font-weight: bold; }

Being Inclusive: Managing Unselected Options

We can bring in some character to our unselected options:

select:not(:checked) > option { opacity: 0.5; // Because fade-out never goes out of style! }