csssassextendextending

How do I directly extend an SCSS parent selector?


I have the following code:

article.featured {
  h4 {
    margin-bottom: 20px
  }
  :first-child {
    height: 100%;
    padding-top: 0;
    padding-left: 0;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    .img {
      @extend &;
    }
  }
  :last-child {
    padding-top: 0;
    padding-right: 0
  }
}

This is line 13:

@extend &;

The problem is that when I try to compile this stylesheet, I get the following error:

Parent selectors aren't allowed here.
  ╷
10│     @extend &;
  │             ^
  ╵
  stdin 13:19 root stylesheet on line 10 at column 19

How can I solve this error and extend the .img element with the parent (&) element's properties?


Solution

  • I've found that it works when I move the .img selector next to the :first-child selector and change the selector to :first-selector, :first-selector .img.

    Here is the working code (NOTE: line 3):

    article.featured {
      h4 { margin-bottom: 20px }
    
      :first-child, :first-child .img {
        height: 100%;
        padding-top: 0;
        padding-left: 0;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
      }
    
      :last-child {
        padding-top: 0;
        padding-right: 0
      }
    }
    

    Which compiles to:

    article.featured h4 {
      margin-bottom: 20px;
    }
    
    article.featured :first-child, article.featured :first-child .img {
      height: 100%;
      padding-top: 0;
      padding-left: 0;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
    
    article.featured :last-child {
      padding-top: 0;
      padding-right: 0;
    }