loading

CSS selector for the previous sibling | 99% chance, No one knows this

As there is now a standard CSS selector for previous siblings provided by CSS or css3. But we can use some tricks to select the previous siblings.

css selector for previous sibling

Using has:()

You can target or select the previous siblings by using has:() and immediate siblings’ selectors.

For example, I want to select 2nd li to color red, for this We can use the logic, to select the child which has an immediate sibling with the class name “.a3”

    <style>
        ul li:has(+ .a3) {
            color: red;
        }
    </style>
    <ul>
        <li class="a1">a1</li>
        <li class="a2">a2</li>
        <li class="a3">a3</li>
        <li class="a4">a4</li>
    </ul>
    Document

    output

    • a1
    • a2
    • a3
    • a4

    Other examples

    Same as the above example we can use all other css selectors with has:() to select different previous or other sibling elements in HTML.

    the following example is to select all previous siblings of the node which has class a3.

     <style>
            ul li:has(~ .a3) {
                color: red;
            }
        </style>
        <ul>
            <li class="a1">a1</li>
            <li class="a2">a2</li>
            <li class="a3">a3</li>
            <li class="a4">a4</li>
        </ul>
    • a1
    • a2
    • a3
    • a4
    👉 Check other advanced css selectors

    About Author

    x

    Order for website design

    Help :