Dima  Lutsik
Dima Lutsik

Reputation: 301

Sass get parent or parent child

There's a better way to do this?

.element{
    &-modifier{
        color: green;
    }

    &:hover{
        .element-modifier{
            color: red;
        }
    }
}

in this case if we change class ".element" on first line
then hover will stop working

i know one solution, but it does not solve the problem completely,

.element{
    $this: &;

    &-modifier{
        color: green;
    }

    &:hover{
        #{$this}-modifier{
            color: red;
        }
    }
}

in this case we need create a lot of variables ($this,$this2,$this3...)

so there's a better way to get parent or parents child?

Upvotes: 1

Views: 3510

Answers (2)

Asons
Asons

Reputation: 87251

Is this logic useful?

Updated fiddle

SASS

.test{
    &-modifier{
        color: green;
    }

    &:hover &-modifier{
        color: red;        
    }
}

HTML

<div class="test">
  <div class="test-modifier">test</div>
</div>

Here is a couple of more variants based on the given comments

.test{
    &-modifier{
        color: green;
    }

    &-modifier2{
        color: green;
    }

    &:hover &-modifier,
    &:hover &-modifier2
    {
        color: red;        
    }}
.test{
    &-modifier{
        color: green;
    }

    &-modifier2{
        color: green;
    }

    &:hover &-modifier2 {
        color: red;        
    }
}
.test{
    &-modifier{
        color: green;
    }

    &-modifier2{
        color: green;
    }

    &-modifier2:hover {
        color: red;        
    }
}

Upvotes: 3

Marvin
Marvin

Reputation: 10122

Here is another solution which does not introduce a variable for the class name but requires you to give up some nesting as you can only access the full parent selector.

.element{
    &-modifier{
        color: green;
    }

    &:hover &-modifier {
        color: red;
    }
}

Output:

.element-modifier {
  color: green;
}
.element:hover .element-modifier {
  color: red;
}

Upvotes: 2

Related Questions