元素水平居中的方法

发布时间 2023-11-06 18:40:50作者: 诶呦你干嘛

1.背景

在开发中经常遇到的问题,让元素的内容在水平和垂直方向上都居中,内容不仅限于文字,可能是图片或者其他元素。

实现居中的方法有很多,可以分为两大类:

  • 居中元素(子元素)的宽高已知
  • 居中元素的宽高未知

2.实现方法

实现元素水平垂直居中的方式;

  • 定位+margin:auto
  • 定位+margin:负值
  • 定位+transform
  • table布局
  • flex布局
  • grid布局

2.1定位+margin:auto

//父元素
.father{
 width:500px;
 height:300px;
 border:1px solid #0a3b98;
 position: relative;
 }
//子元素
 .son{
 width:100px;
 height:40px;
 background: #f0a238;
 position: absolute;
 top:0;
 left:0;
 right:0;
 bottom:0;
 margin:auto;
 }

父元素设置为相对定位,子元素绝对定位,并且四个定位属性值设置为0,此时如果子元素没有设置宽高,则会被拉开到和腹肌一样的宽高。

这里子元素设置了宽高,所以宽高会按照我们的设置来显示,但是实际上子元素的虚拟占位已经撑满了整个父元素,这是再给它一个margin:auto它就可以上下左右都居中了。

2.2定位+margin:负值

 .father {
 position: relative;
 width: 200px;
 height: 200px;
 background: skyblue;
 }
 .son {
 position: absolute;
 top: 50%;
 left: 50%;
 margin-left:-50px;
 margin-top:-50px;
 width: 100px;
 height: 100px;
 background: red;
 }

这种方案不要求知道父元素的宽高,也就是即使父元素的高度变化了,仍然可以保持在父元素的垂直居中位置,水平方向上市一样的操作

但是该方案需要知道子元素自身的宽高,我们可以通过下面transform属性进行移动

2.3定位+transform

.father {
 position: relative;
 width: 200px;
 height: 200px;
 background: skyblue;
 }
 .son {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%,-50%);
 width: 100px;
 height: 100px;
 background: red;
 }

transform(-50%,-50%)会将元素位移自己宽高的-50%

这种方法其实和上边的margin负值用法一样,可以说是margin负值的替代方案,并不需要知道自身元素的宽高

2.4.table布局

.father {
 display: table-cell;
 width: 200px;
 height: 200px;
 background: skyblue;
 vertical-align: middle;
 text-align: center;
 }
 .son {
 display: inline-block;
 width: 100px;
 height: 100px;
 background: red;
 }

设置父元素为display:table-cell,子元素设置display:inline-block。利用vertical和text-align可以让所有的行内块级元素水平垂直居中

2.5.flex弹性布局

.father {
 display: flex;
 justify-content: center;
 align-items: center;
 width: 200px;
 height: 200px;
 background: skyblue;
 }
 .son {
 width: 100px;
 height: 100px;
 background: red;
 }

css3中加入了flex布局,可以非常简单实现垂直水平居中

  • display:flex时,表示该容器内部的元素将按照flex进行布局
  • align-item:center表示这些元素相对于本容器水平居中
  • justify-content:center也是同样的道理垂直居中

2.6.grid网格布局

.father {
 display: grid;
 align-items:center;
 justify-content: center;
 width: 200px;
 height: 200px;
 background: skyblue;
 }
 .son {
 width: 10px;
 height: 10px;
 border: 1px solid red
 }

3.总结

上述方法中不知道元素宽高大小仍能实现水平垂直居中的方法有

  • 定位+margin:auto
  • 定位+transform
  • flex布局
  • grid布局