CSS 实现居中的各种方式

CSS 实现“居中”的各种方式

本文将从盒模型的水平、垂直、水平垂直居中三个方面,总结实现各种方式。



一、水平居中

1、行内/行内块元素 text-align: center

行内/行内块元素的父级盒子指定 text-align: center,可以实现水平居中

2、块级元素 margin: 0 auto

有width,直接使用 margin: 0 auto
无width,需要通过以下方式之一设置水平居中了

  • 设置盒子 display: table,然后使用 margin: 0 auto
  • 设置父级盒子 display: inline-block;然后指定父级盒子 text-align: center

3、父级盒子设置 display: flex; justify-content: center

4、absolute + transform

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
然后给当前盒子进行如下设置:

  • 水平定位距离50%,left: 50%;
  • 水平反向移动自身的宽度一半,已知width用 margin-left: (- width / 2 ) + 'px',未知width用 transform: translateX(-50%)

5、absolute + margin

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
然后给当前盒子左右定位距离设置为0:left: 0; right: 0; margin: auto;

6、直接使用 margin-line: auto

好处是只约束水平上的margin,不约束垂直方向上的margin值。

二、垂直居中

1、行内/行内块元素垂直居中

以下两种方式都能实现行内/行内块元素的垂直居中

  • padding-top === padding-bottom
  • line-height === height

2、多行文本的垂直居中

父级盒子设置 display: table
多行文本设置 display: table-cell; vertical-align: middle

3、父盒子指定 height 并且使用 display: flex; align-items: center;

4、absolute + transform

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
然后对当前盒子进行以下设置:

  • 在垂直方向上设置定位:top: 50%
  • 垂直方向上返向平移自身高度的一半:已知高度 margin-top: (- height / 2) + 'px';,未知高度 transform: translateY(-50%);

5、absolute + margin

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
然后当前盒子上下定位距离为0,设置 top: 0; bottom: 0; margin: auto;

6、margin-block: auto

好处是只约束垂直方向上的margin,不约束水平方向上的margin值。

三、水平垂直居中

1、absolute + margin auto

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
然后定位上下左右都为0,margin值为auto,top: 0; right: 0; bottom: 0; left: 0; margin: auto

2、absolute + 负值margin

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
当前盒子需要有固定width、height: top: 50%; left: 50%; margin-top: (- height / 2) + 'px'; margin-left: (- width / 2) + 'px';

3、absolute + transform

首先子绝父相,当前盒子设置 position: absolute 后,给父级盒子设置 position: relative
当前盒子宽高不限制,top: 50%; left: 50%; transform: translate(-50%, -50%);

4、父级盒子 display: flex; justify-content: center; align-items: center;

5、父级盒子设置 display: table; 当前盒子设置 display: table-cell; text-align: center; vertical-align: center;


总结

上述实现水平居中、垂直居中、水平垂直居中的万能属性就是 transform,是 CSS3 中最具有颠覆性的特征之一,它不会影响其他元素的位置,translate 的百分比值和 rotate 的度数值都是相对于元素自身而言的,对于行内标签没有效果,不会影响其他元素。

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值