如何使用Angular Material实现横向排列卡片
将Angular Material卡片改为水平排列的解决方案
方法一:使用CSS Flexbox(快速实现)
直接修改容器布局属性,即可实现卡片横向排列,这是最简便的方式:
修改后的HTML代码
<body> <div class="wrap"> <div class="text"> <h1 style="font-weight: bold; text-align: center;">Welcome to Data Portal...</h1> <br> <mat-card class="example-card"> <mat-card-header> <mat-card-title>Catalog</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about users/roles.</p> </mat-card-content> <mat-card-header> <mat-card-title>Data Portal</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about all the databases and tables.</p> </mat-card-content> </mat-card> <mat-card class="example-card"> <mat-card-header> <mat-card-title>Data Portal</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about all the databases and tables.</p> </mat-card-content> </mat-card> </div> </div> </body>
修改后的CSS代码
.text { display: flex; gap: 20px; /* 控制卡片之间的间距 */ flex-wrap: wrap; /* 容器宽度不足时自动换行 */ justify-content: center; /* 卡片水平居中排列 */ padding: 0 20px; /* 可选:避免卡片贴容器边缘 */ } .example-card { height: 200px; width: 400px; max-width: 300px; margin: 0; /* 移除原margin-left,改用gap控制间距 */ background-color: lightgrey; color: black; text-align: center; }
方法二:使用Angular Material网格组件(贴合Material设计规范)
如果需要更规整的网格布局,推荐使用Angular Material的mat-grid-list组件:
- 先在Angular模块中导入所需组件:
import { MatGridListModule } from '@angular/material/grid-list'; import { MatCardModule } from '@angular/material/card'; @NgModule({ imports: [ // ...其他导入项 MatGridListModule, MatCardModule ] }) export class YourModule { }
- 修改HTML为网格布局:
<body> <div class="wrap"> <div class="text"> <h1 style="font-weight: bold; text-align: center;">Welcome to Data Portal...</h1> <br> <mat-grid-list cols="2" rowHeight="220px" gutterSize="20px"> <mat-grid-tile> <mat-card class="example-card"> <mat-card-header> <mat-card-title>Catalog</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about users/roles.</p> </mat-card-content> <mat-card-header> <mat-card-title>Data Portal</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about all the databases and tables.</p> </mat-card-content> </mat-card> </mat-grid-tile> <mat-grid-tile> <mat-card class="example-card"> <mat-card-header> <mat-card-title>Data Portal</mat-card-title> </mat-card-header> <mat-card-content> <p>Here you can find the details about all the databases and tables.</p> </mat-card-content> </mat-card> </mat-grid-tile> </mat-grid-list> </div> </div> </body>
- 微调CSS(可选):
.example-card { height: 100%; width: 100%; max-width: unset; /* 取消最大宽度限制,让卡片填满网格单元 */ background-color: lightgrey; color: black; text-align: center; }
说明
- Flexbox方法适合快速调整,无需额外导入模块,灵活性强;
mat-grid-list方法适合需要固定列数、规整布局的场景,更符合Angular Material设计体系。
内容的提问来源于stack exchange,提问作者dude
相关产品推荐
相关产品推荐

