简体   繁体   English

我可以根据使用的类的元素向 SCSS 类添加样式吗?

[英]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.在我的 Angular 13 项目中,我有一个用于两种类型元素的类: <a>标签和<mat-panel-title>标签。 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.我的问题是,我可以为这个类添加一个样式,并以一种只适用于a标签而不适用于其他标签的方式来做。

this is the scss code:这是scss代码:

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

    text-decoration: none;

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

and this is the html:这是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>

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 .或者为不同的元素使用两个单独的类,但本质上是使用@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.其中container__menu--link应用于 a 标签, container__menu--item应用于 mat-panel-title。

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 :如果您只想将样式应用于具有类container__menu--item<a> ,则可以简单地组合选择器,例如a.container__menu--item

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM