居中Centering
样式与布局基础根据内容类型选择合适的居中方法
flex
grid
absolute
什么时候用
- 父容器使用 Flex 时,在两条轴上设置居中登录两个方向都 center,稳稳居中
- 父容器使用 Grid 时,可以用 place-items 居中display: grid + place-items: center,两行收工
- 文字水平居中:text-align: center,只管水平方向标题水平居中text-align: center 只管水平方向
- 定宽块级元素水平居中:margin: 0 auto,见 外边距 Marginmargin: 0 auto,定宽块自动居中
什么时候不用
- 别用 display: table 那套居中:上个时代的招,别学display: table + table-cell,上个时代的招
- 别写一堆 margin 硬凑位置:容器一变宽就歪margin-left: 38px 硬凑,容器一变宽就歪
- 绝对定位居中还要用 transform 修正元素自身尺寸只写 left/top: 50%,元素从中心往右下长
- 块级元素撑满宽度时,自动外边距看不出居中效果宽度没定死,margin: 0 auto 居不了中
组成结构 · Anatomy
元素主轴:justify-content: center交叉轴:align-items: center
1容器Container写上 display: flex 的父元素,居中都是它说了算
2居中元素Centered Item被放到正中间的那个子元素
3主轴对齐Justify Contentjustify-content: center,管主轴方向的居中
4交叉轴对齐Align Itemsalign-items: center,管交叉轴方向的居中
常见变体 · Variants
Flex 居中Flex
普通容器中最常用的居中方法
Grid 居中Grid
父元素已经是 grid 时最省字
绝对定位居中Absolute
老代码里常见,能认出来就行
典型使用场景
登录卡片放页面正中
登录 Vibe
空状态插图居中
暂无收藏
去逛逛,把喜欢的组件收藏起来
标题文字居中
新功能上线
像聊天一样写前端
描述你想要的效果,剩下的交给 AI
定宽容器水平居中