See also:
Quaject
Articles
Topics
How-tos
Drop-down list

Styling native HTML dropdowns

Anton Vasetenkov
Web, data, bio, language.
HTML
CSS

The best way to implement an accessible dropdown in HTML is to use the native <select> element.

This is an example of how to style the native <select> element using JSS:

const useStyles = createUseStyles({
    wrapper: {
        position: 'relative'
    },
    invisibleNativeSelect: {
        position: 'absolute',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,

        width: '100%',
        height: '100%',

        opacity: 0
    },
    visibleDropdown: {
        // Styles for the collapsed dropdown
        fontFamily: 'cursive',

        // Styles for the focused collapsed dropdown
        '$invisibleNativeSelect:focus + &': {
            outline: 2
        }
    }
})

const Dropdown = () => {
    const classes = useStyles()
    const [value, setValue] = useState(options[0].value)

    return (
        <div className={classes.wrapper}>
            <select
                className={classes.invisibleNativeSelect}
                value={value}
                onChange={(event) => setValue(event.target.value)}
            >
                <option value="one">One</option>
                <option value="two">Two</option>
            </select>
            <div className={classes.visibleDropdown}>
                {value}
            </div>
        </div>
    )
}

In the example above, an invisible native <select> element is stretched on top of the visible <div> that renders the currently selected value and can be styled to look like a collapsed dropdown.

See also