首页 > 解决方案 > 为什么更改单个组件的 css 会影响所有其他组件?

问题描述

目标:让 CSS 只影响其所在的组件,而不影响其他组件。我只想影响我的下拉列表,而不是其他文本输入字段:

在此处输入图像描述

背景/问题:我理解为什么它会影响同一页面上的多个项目(mat-form-field)。但不明白为什么它会影响其他页面。我调查了它,但仍然不确定。

我尝试了什么:例如,我最初有:

::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
    height: 40px !important
}

::ng-deep .mat-form-field-infix {
    padding-top: 1px !important;
    padding-bottom: 2px !important;
}

但它影响了页面上所有表单域的间距,所以我将其编辑为

::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
    height: 40px !important
}

::ng-deep .mat-form-field-appearance-outline .mat-form-field-infix {
    padding-top: 1px !important;
    padding-bottom: 2px !important;
}

其他未更改的 CSS:

.title-container {
    position: relative;
    margin-top: 8px;
}

.language-field {
    position: absolute;
    right: 0;
    top: 0;
    margin-top: -16px;
    width: 115px;
    height: 20px !important;
}

这解决了这个问题,但我仍然很奇怪,更改 login.component.css 上的某些内容会影响站点中的所有其他页面,例如 profile.component.css

下面是 login.component 的关联 HTML:

<div class="title-container">
    <mat-card-title class="text-center">
        Please Sign In
    </mat-card-title>

    <form [formGroup]="_siteForm">
        <mat-form-field class="language-field" appearance="outline">
            <mat-select (selectionChange)="changeSite($event)" [value]="languages[i].value">
                <mat-option *ngFor="let language of languages" [value]="language.value">
                    {{language.viewValue}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </form>        
</div> 

当我对此进行研究时:我发现一些 SO 文章(例如Angular 2+:组件样式一直影响其他组件)提到使用封装:ViewEncapsulation 但是,在浏览该站点时,我没有看到它在任何地方使用,但是有在所有提到 mat-form-field 但具有不同值的不同组件上的 css。这似乎表明不需要封装。在常规的 HTML 中,我没有遇到过这些问题,但对它在 Angular 中的工作方式感到困惑。这是否与 Angular 作为 SPA 有关?

标签: cssangular

解决方案


我认为这是你的::ng-deep,删除它。

然后使用特定的类名并在该组件 css 文件中声明它。例如在home.component.css

.mat-form-field-flex {
    height: 40px !important
}

推荐阅读