【问题标题】:Angular Material - Override the overlay css at the component levelAngular Material - 在组件级别覆盖覆盖 css
【发布时间】:2026-02-22 21:35:01
【问题描述】:

我试图在 Angular 组件级别覆盖一些 cdk-overlay css,但它不起作用 - 即使我使用 :host ::ng-deep

这里的材料select (mat-select-content) 是cdk-overlay-pane 的子级:

<div id="cdk-overlay-0" class="cdk-overlay-pane" style="...">
<div class="ng-trigger ng-trigger-transformPanel ng-tns-c19-5 mat-select-panel ng-star-inserted mat-select-panel-done-animating" ng-reflect-klass="mat-select-panel " style="transform-origin: 50% 6.66667px 0px; font-size: 12px; opacity: 1; min-width: calc(100% + 32px); transform: scaleY(1);">
<div class="mat-select-content ng-trigger ng-trigger-fadeInContent" style="opacity: 1;">
	<mat-option _ngcontent-c15="" class="mat-option mat-selected mat-active" role="option" value="Basic" ng-reflect-value="Basic" tabindex="0" id="mat-option-0">
		<span class="mat-option-text">Basic</span>
			<div class="mat-option-ripple mat-ripple"></div>
	</mat-option>
	<mat-option _ngcontent-c15="" class="mat-option" role="option" value="Advanced" ng-reflect-value="Advanced" id="mat-option-1">
		<span class="mat-option-text">Advanced</span><div class="mat-option-ripple mat-ripple"></div>
	</mat-option>
</div>
</div>
</div>

我想将此 css 从我的 main.scss 文件移动到组件级别,因此它不会影响任何其他页面:

.cdk-overlay-container.dark-theme{

    .cdk-overlay-pane, .mat-select-content {    //  search panel
        background: black;
        border: .5px solid #323030;        
    } 
}

但是当我将它移到 my.component.scss 中时,它不起作用:

::ng-deep .cdk-overlay-pane, .mat-select-content {    // search panel
        background: black;
        border: .5px solid #323030;        
    } 

我还需要将此样式添加到我的组件 scss 中的 cdk-overlay-pane 类中:

element.style {
    min-width: 222.333px;
    pointer-events: auto;
    font-size: 12px;
    top: 115px;
    left: 313px;
    transform: translateX(-16px);
}

【问题讨论】:

  • 你不需要加逗号,否则它会把它当作一个新的CSS选择器
  • 对不起,逗号在哪个选择器上?
  • 抱歉,我刚刚仔细看了看,发现这是故意的。你可以试试::ng-deep .cdk-overlay-pane, ::ng-deep .mat-select-content 看看是否有帮助
  • 差不多。我试图将样式隔离到类名.search-dropdown。所以你的建议在这里有效-::ng-deep .search-dropdown .cdk-overlay-pane, ::ng-deep .mat-select-content,但这不是::ng-deep .search-dropdown .cdk-overlay-pane, ::ng-deep .search-dropdown .mat-select-content。好奇怪。
  • 问题是如果我不使用正确的类层次结构,我很容易影响其他叠加层中的其他页面......

标签: angular angular-material angular-material-6


【解决方案1】:

覆盖容器内的内容不能在组件内设置样式,因为覆盖内容不是组件的子组件。覆盖容器是页面body 元素的子元素,因此其内容的样式需要驻留在您的全局样式中。但是,您可以使用MatSelectpanelClass 属性有选择地将样式应用于覆盖容器内的特定选择面板:

<mat-select panelClass="my-panel-class">...

.my-panel-class .mat-select-content {
    background: black;
    border: .5px solid #323030;        
} 

【讨论】:

  • 我会试试看的。
  • 这也是正确的答案,因为重新设置共享类(例如cdk-overlay-pane)会导致unintended consequences