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

Angular 2+Angular Material两按钮同排及中间竖线实现问题求助

解决Angular Material中Sign In/Sign Up按钮同行并加竖线分隔的问题

我来帮你搞定这个问题!在Angular Material里实现两个按钮同行并加竖线分隔,用Flex布局是最稳妥的方式,不管你用Angular官方的FlexLayout模块还是原生CSS Flex都能轻松实现,下面是具体方案:

方案一:使用Angular FlexLayout模块(推荐,贴合Material生态)

1. 先确保安装并导入FlexLayout

如果还没安装,先执行命令:

npm install @angular/flex-layout @angular/cdk

然后在你的app.module.ts中导入模块:

import { FlexLayoutModule } from '@angular/flex-layout';

@NgModule({
  imports: [
    // ...其他导入
    FlexLayoutModule
  ]
})
export class AppModule { }

2. 调整HTML结构

用flex容器包裹两个按钮,中间插入分隔线元素:

<div class="textAlign">
  <div fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="16px">
    <button mat-raised-button color="primary">Sign In</button>
    <div class="vertical-divider"></div>
    <button mat-raised-button color="accent">Sign Up</button>
  </div>
</div>

3. 添加分隔线样式

在你的CSS文件中补充:

.textAlign {
  text-align: center;
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-family: 'Source Sans Pro', sans-serif;
}

.vertical-divider {
  width: 1px;
  height: 32px; /* 匹配按钮高度,可根据你的按钮样式调整 */
  background-color: white; /* 可根据主题修改颜色,比如用半透明白色更柔和 */
}

方案二:使用原生CSS Flex(无需额外模块)

如果不想引入FlexLayout模块,用原生CSS也能实现:

1. HTML结构

<div class="textAlign">
  <div class="auth-buttons">
    <button mat-raised-button color="primary">Sign In</button>
    <div class="vertical-divider"></div>
    <button mat-raised-button color="accent">Sign Up</button>
  </div>
</div>

2. CSS样式

.textAlign {
  text-align: center;
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-family: 'Source Sans Pro', sans-serif;
}

.auth-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px; /* 按钮与分隔线的间距 */
}

.vertical-divider {
  width: 1px;
  height: 32px;
  background-color: rgba(255,255,255,0.7); /* 半透明白色,视觉效果更友好 */
}

为什么之前的尝试可能失败?

  • 按钮默认可能是块级元素(不过Angular Material的按钮默认是inline-block,但如果没有容器包裹,可能会因为父元素的文本对齐方式导致换行)
  • 分隔线元素没有设置合适的宽高和背景色,导致看不到
  • 没有用Flex布局来控制元素的水平排列

你可以根据自己的按钮样式调整分隔线的高度和颜色,比如如果用的是mat-button(不是凸起按钮),可以把分隔线的height改成24px,或者用margin: 8px 0让分隔线和按钮自然对齐~

内容的提问来源于stack exchange,提问作者Mat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:34:07