Angular 6中如何将内容居中显示在Mat-Card组件内
Fixing Centered Content in Angular Material Card
Hey there! Let's get your mat-card's image and button centered properly. The key issue here is that your .dashboard-card-content wasn't set up as a flex container—those justify-content rules only work when flexbox is enabled. Here's a straightforward fix:
Updated CSS
.grid-container { margin: 20px; } .dashboard-card { position: absolute; top: 15px; left: 15px; right: 15px; bottom: 15px; max-width: 150px; min-width: 150px; display: flex; flex-direction: column; } .dashboard-card-content { flex: 1; display: flex; flex-direction: column; align-items: center; /* Centers items horizontally */ justify-content: center; /* Centers items vertically in the content area */ gap: 1rem; /* Adds space between image and button (adjust as needed) */ } /* Optional: Prevent image from overflowing the card */ .dashboard-card-content img { max-width: 100%; height: auto; }
What Changed?
- Added
display: flexandflex-direction: columnto.dashboard-cardso the card's content area uses the full available vertical space. - Turned
.dashboard-card-contentinto a flex container with vertical stacking (flex-direction: column):align-items: centermakes sure the image and button are centered horizontally.justify-content: centercenters them vertically inside the content section.
- The
gapproperty adds clean spacing between the image and button—you can tweak the value to match your design. - The optional image styling ensures your image doesn't stretch beyond the card's width.
Bonus: Angular Best Practice Tweak
For better security and Angular compliance, use property binding for src and href instead of interpolation in your HTML:
<mat-card-content class="dashboard-card-content"> <img [src]="card.IMGPath" alt="{{card.title}}"> <!-- Added alt text for accessibility too! --> <a mat-raised-button color="primary" [href]="card.ButtonLink">{{card.ButtonLabel}}</a> </mat-card-content>
This should make your card content look perfectly centered, both horizontally and vertically.
内容的提问来源于stack exchange,提问作者PCorruthers
相关产品推荐
相关产品推荐

