Skip to content

Instantly share code, notes, and snippets.

@kvlsrg
Last active January 4, 2023 09:57
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kvlsrg/49b09e7d9040583cd33576ad0dd299ea to your computer and use it in GitHub Desktop.
Save kvlsrg/49b09e7d9040583cd33576ad0dd299ea to your computer and use it in GitHub Desktop.
Parent of parent in Sass

How to get parent of parent in Sass

You can just get it from cached &. Here is a simple BEM example:

HTML

<ul class="pagination">
  <li class="pagination__item">
    <a class="pagination__link" href="#">
      Page 1
    </a>
  </li>
  <li class="pagination__item pagination__item--active">
    <a class="pagination__link" href="#">
      Page 2
    </a>
  </li>
</ul>

SCSS

$gray-very-light: #ccc;

.pagination {
  display: flex;
  padding: 0;
  list-style: none;

  $this: &;

  &__item {
    border: 1px solid $gray-very-light;

    & + & {
      margin-left: .5rem;
    }
  }

  &__link {
    display: block;
    padding: .25rem .5rem;
    text-decoration: none;

    &:hover,
    #{$this}__item--active & { // Here we get .pagination from $this variable
      background-color: $gray-very-light;
    }
  }
}

Output CSS

.pagination {
    display: flex;
    padding: 0;
    list-style: none;
}

.pagination__item {
    border: 1px solid #ccc;
}

.pagination__item + .pagination__item {
    margin-left: .5rem;
}

.pagination__link {
    display: block;
    padding: .25rem .5rem;
    text-decoration: none;
}

.pagination__link:hover,
.pagination__item--active .pagination__link {
    background-color: #ccc;
}
@serrrgggeee
Copy link

#{$this} not working for me, I even update sass to version 1.26.5

@kvlsrg
Copy link
Author

kvlsrg commented May 15, 2020

@serrrgggeee You added this in scope of parent?

$this: &;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment