Explain Codes LogoExplain Codes Logo

Problem with `` and :after with CSS in WebKit

web-development
responsive-design
best-practices
accessibility
Alex KataevbyAlex Kataev·Oct 3, 2024
TLDR

To add styles or icons, such as a dropdown arrow to a <select> element, encase it within a <div>. This approach allows you to apply the :after pseudo-element on the wrapper instead of the <select>—which is incompatible with :after in WebKit.

CSS:

.select-wrapper:after { content: '▼'; /* This is your divine arrow of selection 😌 */ position: absolute; right: 10px; /* Feel free to experiment with this! 👩‍🔬 */ pointer-events: none; /* Clicks on the arrow will still focus the select — pretty neat, huh? */ }

HTML:

<div class="select-wrapper"> <select>...</select> </div>

This solution provides a consistent style across different browsers reality without modifying the innate behavior of the <select> element.

Why select styling is tricky

Styling native <select> elements can be a convoluted task. Here's the catch: they are rendered at the operating system level, not the browser. Each operating system has its unique styling for the <select> element. That's why not all CSS rules apply to them, including the :after pseudo-element—WebKit-based browsers (like Safari and Chrome) won't have it. So, what's the workaround? Read on.

When standard CSS isn't enough

This is where creative solutions come in handy. JavaScript-based solutions or libraries such as Select2 or Chosen provide more control over styling and functionality. They create custom-markup structures in place of native elements, offering you a canvas to paint your <select> field however you like.

Being compatible and accessible at same time

However, we can't just care about aesthetics, right? What about users who navigate our page with keyboard or screen readers? That's why we soulfully dedicate these accessibility and compatibility considerations.

Customizing with wrapper elements

Our original solution covered the use of wrapper elements. You don’t style the <select> directly, but its parent, with the help of CSS pseudo-elements. This way, you apply styles to a custom container, transforming it into anything — drop-down arrows, borders, custom backgrounds, you name it!

Keeping it accessible

As Spiderman's Uncle Ben said, with great power comes great responsibility. As we style forms creatively, we need to maintain their accessibility. Focus states, keyboard navigation, screen-reader support — all these aspects are as important as our design.

SVG and appearance properties

You could also use -webkit-appearance: none; to remove the default dropdown arrow and introduce an SVG via background-image.

Example:

.select-style { -webkit-appearance: none; /* Goodbye, old dropdown arrow 🙋‍♂️ */ background-image: url('data:image/svg+xml;utf8,<svg...'); }

Just ensure that the SVG content in the background-image is URL-encoded to avoid any potential parsing issues.