首页 新闻 会员 周边

angular: scss 样式不起作用

0
悬赏园豆:30 [已解决问题] 解决于 2023-08-01 15:26

下面的 scss 代码中,mat-icon 样式起作用,svg 样式不起作用,请问如何解决?

.branding {
  mat-icon {
    width: auto;
    height: auto;
  }

  svg {
    height: 28px;
    width: auto;
    margin-left: 10px
  }
}

对于的 html 代码:

<ul class="navbar-list navbar-left">
  <li class="branding">
    <a href="/" title="开发者的网上家园">
      <mat-icon svgIcon="logo"></mat-icon>
    </a>
  </li>
</ul>
问题补充:

生成的 css 代码是这样的

mat-icon[_ngcontent-iyc-c24]{width:auto;height:auto}
.branding[_ngcontent-iyc-c24] svg[_ngcontent-iyc-c24]{height:28px;width:auto;margin-left:10px}

svg 选择器多了个 [_ngcontent-iyc-c24]

dudu的主页 dudu | 高人七级 | 园豆:30948
提问于:2023-08-01 14:29
< >
分享
最佳答案
0

在 Angular 中,如果使用了 mat-icon 组件来显示 SVG 图标,需要确保已经正确引入了 MatIconModule 模块,并且已经导入了相应的图标。

  1. 检查 SVG 图标的样式类名:在 Angular Material 中,mat-icon 组件会为 SVG 图标添加一些样式类名,例如 mat-iconmat-icon-inline。可以使用浏览器的开发者工具检查生成的 HTML 代码,确保 SVG 图标的样式类名正确。

  2. 使用 ::ng-deep/deep/:如果 SVG 图标的样式受到了父级组件的样式影响,可以尝试使用 ::ng-deep/deep/ 来穿透组件样式的封装,使得样式能够应用到 SVG 元素上。例如:

    .branding {
      ::ng-deep svg {
        height: 28px;
        width: auto;
        margin-left: 10px;
      }
    }
    
  3. 使用 encapsulation: ViewEncapsulation.None:如果 SVG 图标的样式受到组件的样式封装影响,可以尝试在组件中设置 encapsulation: ViewEncapsulation.None,以取消样式封装。请注意,取消样式封装可能会导致全局样式冲突和样式泄漏的问题,需要谨慎使用。例如:

    import { Component, ViewEncapsulation } from '@angular/core';
    
    @Component({
      selector: 'app-example',
      templateUrl: 'example.component.html',
      styleUrls: ['example.component.scss'],
      encapsulation: ViewEncapsulation.None
    })
    export class ExampleComponent { }
    

尝试以上解决方案后,重新编译和运行 Angular 应用,查看 SVG 图标的样式是否生效。如果问题仍然存在,可以进一步检查代码和调试,确保没有其他样式或组件逻辑导致 SVG 样式不起作用。

收获园豆:30
lanedm | 老鸟四级 |园豆:2381 | 2023-08-01 14:37

::ng-deep 可以解决

.branding {
  ::ng-deep svg {
    height: 28px;
    width: auto;
    margin-left: 10px;
  }
}
dudu | 园豆:30948 (高人七级) | 2023-08-01 15:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册