Search code examples
csssassstyling

How can I access the grandparent element with SCSS?


I have a structure like this:

<div class="input-wrapper"> 
    <input placeholder="Full name">
    <label>
        <span>*</span>
        <span>Full name</span>
    </label>
</div>

I want to hide the second span of the label with SCSS, when I do a focus on input field.

I tried to:

.input-wrapper{
    $this: parent;

    ...

    input{
        &:focus{
            parent > label > span:nth-child(2){
                display: none;
            }
        }
    }
}


.input-wrapper{
    ... 

    input:focus{
        .input-wrapper__label > span:nth-child(2){
            display: none;
        }
    }
}

Maybe I could do something with label > span:nth-child(2) with if?


Solution

  • To achieve expected result, you can use below option of adjacent sibling selector(+) of targeting label on input focus
    input:focus + label > span:nth-child(2)

    Sample code below and codepen - https://codepen.io/nagasai/pen/PoBLBBm for reference

        input:focus + label > span:nth-child(2){
                display: none;
            }
    <div class="input-wrapper"> 
        <input placeholder="Full name">
        <label>
            <span>*</span>
            <span>Full name</span>
        </label>
    </div>