You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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: flex and flex-direction: column to .dashboard-card so the card's content area uses the full available vertical space.
  • Turned .dashboard-card-content into a flex container with vertical stacking (flex-direction: column):
    • align-items: center makes sure the image and button are centered horizontally.
    • justify-content: center centers them vertically inside the content section.
  • The gap property 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:04:32