CSS Previous Sibling Selector


There is no previous sibling selector in CSS. Instead, we can achieve the same behavior by using flexbox and the order property.

Let's say you're adding a prefix to an input, and would like to style the prefix when the input is focused. If you read from left to right and top to bottom (English), you likely structure your DOM like that too:

<div class="container"> <div class="prefix">https://</div> <input type="text" /> </div>

In this markup, there's no way to target the .prefix class using input:focus, because we have no preceding selector. Instead, we can rewrite the DOM structure so that prefix appears after the input:

<div class="container"> <input type="text" /> <div class="prefix">https://</div> </div>

And use flexbox to change the order of appearance:

.container { display: flex; } .container input { order: 1; } .container .prefix { order: 2; }

Now you can select the prefix using the sibling selector:

.container input:focus + .prefix { /* Focus styles... */ }

In the case of an input, the simple solution is to use :focus-within, which has good browser support but is still experimental. Maybe you have other use cases for this trick though, let me know!

This post is inspired by my own work on inputs, and this paragraph:

Unfortunately, trying to use :focus limits what you can do: you can style the input or siblings that come after the input… but that’s it. — Initializing focus state in React