几种元素水平垂直居中的方法

83 阅读1分钟

前言

在平时开发以及面试中,我们经常会遇到元素水平垂直居中的问题,下面我们就来讲解下元素居中的一些解决方法。哈哈哈哈哈,第一次写文章,写得不好的地方请多多包涵哈!

行内元素

对于子元素为行内元素,想实现其在父元素中水平居中,只需为其父元素设置 text-align: center;即可。若想实现其在父元素中垂直居中,只需为其父元素设置 line-height: 父元素高度;即可。

块级元素

对于子元素为块级元素,想实现其在父元素中水平居中,只需为其本身设置 margin: 0 auto;即可。

下面我们来综合讲一下元素水平垂直居中的方法。

(1)使用绝对定位以及margin,前提是子元素宽度、高度固定。

.child {
   width: 100px;
   height: 100px;
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   margin: auto;
}

(2)使用绝对定位以及margin-topmargin-left,前提是子元素高度、宽度固定。

.child {
   width: 100px;
   height: 100px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-top: -50px;
   margin-left: -50px;
}

(3)使用绝对定位以及transform

.child {
   width: 100px;
   height: 100px;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
} 

(4)使用flex弹性布局,为其父元素设置:

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
}