css - 为什么更改单个组件的 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 有关?
解决方案
我认为这是你的::ng-deep
,删除它。
然后使用特定的类名并在该组件 css 文件中声明它。例如在home.component.css
.mat-form-field-flex {
height: 40px !important
}
推荐阅读
- c++ - 在 Windows 上管道到 ffmpeg
- python - Pygame 与 cx_Freeze 一起使用,但当我运行可执行文件时,窗口中没有显示任何内容
- python - 有没有办法将 mxn 矩阵(1)与 pxn 矩阵(2)批量相乘,其中矩阵(2)的每一行都是标量?
- python - 为什么此替换方法无法正常工作
- python - 从 100 开始数到 999
- r - R:计算基函数的惩罚矩阵?
- swift - iOS 11 SDK:AVPlayerViewController 不等同于 willEndFullScreenPresentationWithAnimationCoordinator 被调用
- regex - 使用列表跳过字典中的数字/单词组合
- php - 如何保存 PHP 变量 $SAddress1 = "1234 My Address" 以便稍后在表单字段中的网站上使用 3 页?Apache、PHP、MySql 网站
- c# - 我的传送脚本导致我的玩家随机传送回集线器