如何使用CSS整齐堆叠日期属性(Angular通知卡片场景)
调整通知卡片日期显示样式的方法
问题
我开发的Angular应用里,通知卡片的日期显示不够规整,日部分偏左,想让它稍向右移,整体堆叠更整齐。相关代码如下:
HTML结构
<div> <mat-card *ngFor="let notification of notifications"> <div class="notif-card"> <h4 class="startDate">{{formatDate(notification.start_date)}}</h4> <h4 class="name">{{notification.payor_name}}</h4> <div class="card-desc"> <h4 class="linkText" (click)="getDocUrl(notification.doc_id)">{{domParser(notification.name)}}</h4> <button class="notes" (click)="navigateToNotes(notification.id)">View Notes</button> </div> </div> <hr> </mat-card> </div>
当前.startDate样式
.startDate { border-right: 3px solid #f2c413; height: 60px; justify-content: center; margin-right: 10px; padding-right: 50px; width: 5%; }
完整CSS参考
@admin-link-blue: #0078D3; .notif-menu { width: 100%; margin-top: 4%; background: #f4f4f4; padding-bottom: 5px; } .page-title { padding-top: 20px; } .menu-title { padding-top: 20px; } .menuPart { background: var(--bs-body-bg); padding-bottom: 30px; } .heading { font-weight: bold; } .search { margin-top: 25px; background: #009aa6; color: white; } .startDate { border-right: 3px solid #f2c413; height: 60px; justify-content: center; margin-right: 10px; padding-right: 50px; width: 5%; } .name { border-right: 1px solid gray; height: 100px; justify-content: center; color: #797979; letter-spacing: 0.25rem; font-size: 1rem; overflow: hidden; text-overflow: ellipsis; margin-top: 10px; width: 15%; } .notif-card { display: flex; align-items: center; gap: 20px; } .card-desc { width: 80%; } .linkText { color: #0078d5; cursor: pointer; } .notes { background:none; border:none; cursor: pointer; font-weight: bold; color: #009aa6; } .paging-wrap { height: 90px; display: flex; align-items: center; justify-content: center; .clickable { cursor: pointer; color: @admin-link-blue; &:hover { text-decoration: underline; } } i.fa, .page-info { padding: 5px; font-size: 20px; } }
解决方法
直接修改.startDate的CSS样式,通过flex布局控制内部文本的对齐:
.startDate { border-right: 3px solid #f2c413; height: 60px; /* 开启flex垂直布局,让日期行堆叠 */ display: flex; flex-direction: column; /* 水平右对齐,让日部分靠右 */ align-items: flex-end; justify-content: center; margin-right: 10px; /* 调整内边距,避免过大留白 */ padding: 0 12px 0 0; /* 固定宽度,保证所有日期块一致 */ width: 60px; /* 文本强制右对齐 */ text-align: right; }
调整要点:
- 用
flex-direction: column让日期的月、日、年垂直排列,替代默认的块级布局,更易控制对齐 align-items: flex-end和text-align: right双管齐下,确保每一行文本都靠右,实现日部分右移的需求- 把百分比宽度改成固定的
60px,避免屏幕宽度变化导致布局错位,所有日期块宽度统一 - 去掉不合理的
padding-right: 50px,换成小的右侧内边距,让内容和右侧黄线的间距更合理
只要formatDate方法返回的日期是换行分隔的(比如用<br>或者换行符),这个样式就能直接生效,让日期整体堆叠规整,日部分靠右对齐。
内容的提问来源于stack exchange,提问作者Cole Perry
相关产品推荐
相关产品推荐

