如何在PrimeNG 9.1.3与PrimeFlex 1.3.0中实现登录表单垂直水平居中
问题原因
- PrimeFlex 1.3.0 中
p-align-center类的作用是对齐p-grid容器的直接子元素(也就是两个p-col列)的垂直位置,无法影响列内部的表单内容布局。 - 你给右侧带背景的列设置了
height:100%撑满高度,但这个列默认是块级元素,内部的表单默认按块流顶对齐、左对齐,没有触发居中逻辑。
修复方案
直接给右侧带背景的p-col-6加上PrimeFlex提供的flex布局工具类,让这个列本身成为flex容器,居中内部内容即可,不需要额外写重复的内联样式:
<div class="p-grid" style="height: 100vh"> <div class="p-col-6" style="text-align: center"> <h2>Sample app</h2> </div> <!-- 新增 p-d-flex p-ai-center p-jc-center 三个类 --> <div class="p-col-6 p-d-flex p-ai-center p-jc-center" style="background-color: #f1f1f2;"> <div> <form> <h4>LOGIN</h4> <span class="ui-float-label"> <input id="float-input" type="email" size="50" pInputText /> <label for="float-input">Email</label> </span> <div style="margin-top: 25px"></div> <span class="ui-float-label"> <input id="float-input" type="password" size="50" pInputText /> <label for="float-input">Password</label> </span> <div style="margin-top: 25px"></div> <p-button label="Login" styleClass="ui-button-success"></p-button> </form> </div> </div> </div>
新增类的作用说明:
p-d-flex:给列设置display: flex,将其转换为flex容器p-ai-center:设置align-items: center,实现内部内容的垂直居中p-jc-center:设置justify-content: center,实现内部内容的水平居中
注意:如果上述类不生效,先检查项目是否正确引入了PrimeFlex的核心CSS文件,通常需要在
angular.json的styles配置中添加路径:node_modules/primeflex/primeflex.css,再重启开发服务。
额外调整说明
- 移除了原外层容器的
p-align-center类,因为两个列都需要撑满整个100vh高度,不需要单独对齐列的位置 - 移除了右侧列原来的
height:100%内联样式,外层p-grid已经设置为100vh高度,p-col作为grid的子元素默认会自动撑满交叉轴高度,不需要手动设置
内容的提问来源于stack exchange,提问作者Dheepak S
相关产品推荐
相关产品推荐

