Angular中使用CSS Grid按列索引设置4列网格对齐的方案咨询
优先推荐CSS原生方案(无JS逻辑)
直接通过CSS :nth-child 选择器按4列的周期匹配对应列的元素即可,无需额外的TS计算逻辑,也不需要给模板绑定动态样式,性能和可维护性更佳。
简化后的HTML代码
你可以直接移除原来的[ngStyle]绑定和getTextAlign方法:
<div class="expander-content"> <p *ngFor="let service of location.services; let i = index">{{service.name}}</p> </div>
完整SCSS代码
.expander-content{ display: grid; grid-auto-rows: 1fr; grid-template-columns: 1fr 1fr 1fr 1fr; /* 匹配每一行第一列 */ p:nth-child(4n + 1) { text-align: start; /* 若要用网格原生对齐属性替换文本对齐,改成 justify-self: start; 即可 */ } /* 匹配每一行中间两列 */ p:nth-child(4n + 2), p:nth-child(4n + 3) { text-align: center; /* 同上可替换为 justify-self: center; */ } /* 匹配每一行最后一列 */ p:nth-child(4n + 4) { text-align: end; /* 同上可替换为 justify-self: end; */ } }
原JS逻辑修正方案
如果你确实需要在TS层控制对齐逻辑,只要把原来的模运算改成按4取模即可,你之前的错误是用了模3、模2的判断,不符合4列的周期规律:
getTextAlign(index: number): string { // 4列布局,按4取模得到当前元素所在列,0为第一列,3为第四列 const colIndex = index % 4; if (colIndex === 0) return 'start'; if (colIndex === 1 || colIndex === 2) return 'center'; return 'end'; }
内容的提问来源于stack exchange,提问作者Brandon Miller
相关产品推荐
相关产品推荐

