Newsha Nik
Newsha Nik

Reputation: 947

Can I add a style to an SCSS class based on the element the class in used on?

In my Angular 13 project, I have a class I'm using on two types of elements: <a> tags and <mat-panel-title> tags. My question is, can I add a style to this class and do it in a way that it will only apply to the a tags and not the other ones.

this is the scss code:

.container__menu--item {
    display: flex;
    align-items: center;

    text-decoration: none;

    span {
      padding-inline-start: 8px;
    }
  }

and this is the html:

 <a class="container__menu--item" href="#">
    <mat-icon>home</mat-icon>
    <span>{{ 'navbar.main_page' | transloco }}</span>
  </a>

  <mat-accordion>
    <mat-expansion-panel>
      <mat-expansion-panel-header>
        <mat-panel-title class="container__menu--item">
          <mat-icon svgIcon="services"></mat-icon>
          <span>{{ 'navbar.services' | transloco }}</span>
        </mat-panel-title>
      </mat-expansion-panel-header>
      <ul>
        <li>
          {{ 'navbar.services' | transloco }}
        </li>
        <li>
          {{ 'navbar.services' | transloco }}
        </li>
      </ul>
    </mat-expansion-panel>
  </mat-accordion>

Upvotes: 0

Views: 49

Answers (2)

biberman
biberman

Reputation: 5777

If you only want to apply styles to an <a> with the class container__menu--item, you simply could combine the selectors like a.container__menu--item:

a.container__menu--item {
    ... /* your styles */
}

Upvotes: 0

princess_hacker
princess_hacker

Reputation: 575

You could do either

.container__menu--item {
    <shared style>

    a {
      <specific style>
    }
}

Or use two separate classes for the different elements but essentially copy the style of one to the other using @extend. This would for example look like

.container__menu--link {
    @extend .container__menu--item
 }

where container__menu--link is applied to the a tag and container__menu--item to mat-panel-title.

Upvotes: 1

Related Questions