Skip to content

Instantly share code, notes, and snippets.

@kvlsrg
Last active October 30, 2024 18:50
Show Gist options
  • 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