Angular自定义子组件无法生效父容器:first-child、:last-child样式
问题根源
拆分子组件后,.conteneur的直接子节点从原来的mat-card变成了app-child-*自定义元素,你原来写在.first_or_last_child里的:last-child/:first-child伪类,作用对象错误:
- 如果你把
.first_or_last_child加在子组件内部的mat-card上,每个mat-card都是对应子组件里的唯一子节点,所以永远同时命中首、末子节点规则,伪类逻辑失效 - 如果你把类加在
app-child-*标签上,原来的样式里宽度等属性同时作用于宿主标签和内部的mat-card,相当于两层宽度计算,导致子组件无法占满空间
解决方案1(推荐:样式职责拆分清晰)
- 父级HTML保持给子组件加类的写法即可:
<div class="conteneur"> <app-child-first class="first_or_last_child"></app-child-first> <app-child-second class="first_or_last_child"></app-child-second> <app-child-third class="first_or_last_child"></app-child-third> </div>
- 调整
.first_or_last_child类,仅保留全局布局相关属性,移除mat-card内部相关样式:
.first_or_last_child { width: 28%; margin-right: 1.5%; min-width: 276px; margin-bottom: 3%; display: block; &:last-child { margin-right: 0 !important; } -webkit-box-shadow: 0 3px 6px rgba(0, 0, 0, .16); -moz-box-shadow: 0 3px 6px rgba(0, 0, 0, .16); box-shadow: 0 3px 6px rgba(0, 0, 0, .16); }
- 子组件内部新增宿主样式,同时把
mat-card相关的内部样式挪到子组件CSS中,去掉内部mat-card上的.first_or_last_child类:
/* 子组件CSS */ :host { width: 100%; height: 100%; display: block; } mat-card { width: 100%; height: 100%; display: flex; flex-direction: column; border-radius: 8px; /* 剩下的mat-list、mat-card-header、mat-list-item相关的原有样式都挪到这里即可 */ }
解决方案2(快速修复:无需拆分原有样式)
不用调整HTML结构和原有样式代码,仅在全局CSS中新增两条选择器,直接命中首末子组件内部的mat-card即可:
/* 全局CSS添加 */ .conteneur > *:first-child .first_or_last_child { /* 首个子元素需要的特殊样式 */ } .conteneur > *:last-child .first_or_last_child { margin-right: 0 !important; }
内容的提问来源于stack exchange,提问作者Lainea
相关产品推荐
相关产品推荐

