Takuhii
Takuhii

Reputation: 925

Can I Prepend an Element in SASS?

I understand that in SASS I can do this;

h3 {
  font-size: 20px
  margin-bottom: 10px

  .some-parent-selector & {
        font-size: 24px
        margin-bottom: 20px
  }
}

to produce this code;

h3 {
  font-size: 20px;
  margin-bottom: 10px;
}
.some-parent-selector h3 {
  font-size: 24px;
  margin-bottom: 20px;
}

Does anyone know how I could achieve this with an element? Basically I want to do this in SASS;

.some-parent-selector {
    font-size: 24px
    margin-bottom: 20px

    a& {
        ...
    }
}

to produce this code;

.some-parent-selector {
    font-size: 24px
    margin-bottom: 20px
}
a.some-parent-selector {
    ...
}

I am seeing an issue where I can only do this if I put a space between the element and the ampersand. If I don't the linter fails, but I guess deep down SASS doesn't understand it.. Or I need to format it better...

I need this because I am working with some code, where a selector appears within the page, but every so often it is assigned to a Anchor tag...

Any help or advise would be greatly appreciated?

Upvotes: 3

Views: 1536

Answers (1)

user4994625
user4994625

Reputation:

I try use interpolation:

SASS

  .some-parent-selector {
        font-size: 24px;
        margin-bottom: 20px;

       a#{&}{
            margin-bottom: 20px
        }
    }

But the parent repeat and I get this:

output

.some-parent-selector {
  font-size: 24px;
  margin-bottom: 20px;
}
.some-parent-selector a.some-parent-selector {
  margin-bottom: 20px;
}

so I extract the selector from his parent with @at-root directive:

SASS

.some-parent-selector {
    font-size: 24px;
    margin-bottom: 20px;

   @at-root a#{&}{
        margin-bottom: 20px
    }
}

output

.some-parent-selector {
  font-size: 24px;
  margin-bottom: 20px;
}
a.some-parent-selector {
  margin-bottom: 20px;
}

Upvotes: 9

Related Questions