E
E
Elena Valentine2020-09-02 19:08:08
Sass
Elena Valentine, 2020-09-02 19:08:08

How to implement class nesting in SCSS?

There is some markup like this:

<div class="card">
  <figure class="card__avatar">
    <im class="card-avatar__image" src="" />
  </figure>
</div>


What is the correct way to refer to the child element of the card_avatar selector if the name of the child element changes like this card-avatar__image ? i.e. when you try to access it like this:

.card {
  &__avatar {
    &__image {
    }
  }
}


There are no results. Is there any normal way to solve this while keeping the SCSS syntax? I'm interested in the option in which it will be possible to do deeper nesting, i.e. for example, something like this:

<div class="card">
  <div class="card__block">
    <div class="card-block__inner">
      <div class="card-block-inner__box">
        <div class="card-block-inner-box__item">

        </div>
      </div>
    </div>
  </div>
</div>


.card {
  &__block {
    &__inner {
      &__box {
        &__item {
        }
      }
    }
  }
}


Is it possible to do it or not? Maybe there are still some options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey ZSA, 2020-09-02
@serjikz

You have already been told in the comments that the approach is terrible and it's all wrong, etc., etc. But if you really really and really want to write bad code, no one will forbid you to do this.
What could be the solution - you can make a variable inside the parent. That is, like this:

.card {
  $parent: ".card";

  &__avatar {
    $avatar: ".#{$parent}-avatar";

    #{$avatar}__image {
        // ну и далее я думаю подход ясен
    }
  }
}

Nobody argues that maybe the mixin will come in somehow, but now I don’t want to mess with it (and I don’t see the point at all).
You can poke all the variables of possible names right at the very beginning and combine everything you need from them (just on the basis of this, you can try to cut a mixin with a cycle, and so on and so forth).
But honestly, it's better to use BEM and everything that it promotes. If you write in your profile that you are a front-end - please act like a front-end and don't write bad code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question