前端垂直水平居中几种经典做法

1,000 阅读2分钟

在页面布局中,还只会使用 margin:0 auto 和 text-align:center?

一、盒子--块级元素居中

1. 盒子水平居中

1)实现块级元素水平居中,最简单的做法当然还是我们最熟悉的margin:0 auto;

    .box{
      margin: 0 auto;
      width: 100px;
      height: 100px;
      background-color: pink;
    }

实现效果:

image.png

2)借助定位实现块级元素水平居中

.box{
      /* 绝对定位 */
      position: absolute;
      left: 50%;
      width: 100px;
      height: 100px;
      background-color: pink;
    }

image.png

此时盒子并未居中,要想盒子居中还需要将盒子左移,此处有两种方法可实现左移

①通过位移属性transform移动盒子

     /* 水平向左移动元素本真的50% */
      transform: translateX(-50%);

②通过margin-left移动盒子

 margin-left: 50px;

完整实现代码如下

.box{
      /* 绝对定位 */
      position: absolute;
      left: 50%;
      /* 水平向左移动元素本真的50% */
      /* transform: translateX(-50%); */
      margin-left: 50px;
      width: 100px;
      height: 100px;
      background-color: pink;
    }

2. 盒子垂直居中

实现块级元素垂直居中: 1)借助定位+ 位移属性实现 2)定位+margin

1)

.box{
      /* 绝对定位 */
      position: absolute;
      left: 0;
      /* 距上边距父元素高度的50% */
      top: 50%;
      /* 向上位移盒子本身的50% */
      transform: translateY(-50%);
      width: 100px;
      height: 100px;
      background-color: pink;
    }

2)

.box{
      /* 绝对定位 */
      position: absolute;
      left: 0;
      /* 距上边距父元素高度的50% */
      top: 50%;

      margin-top: -50px;
      
      width: 100px;
      height: 100px;
      background-color: pink;
    }

image.png

二、文本、行内元素居中方法

1. 文本居中:(1)文本水平居中 (2)单行文本垂直居中

div{
      width: 400px;
      height: 400px;
      background: greenyellow;
      /* 水平居中  文字的父元素 text-align */
      text-align: center;
      /* 
      前提:文字单行
      实现垂直居中:设置行高属性值 = 自身高度属性值 */
      line-height: 400px;
    }

image.png

2.行内元素水平居中

水平居中实现

.box{
      background-color: red;
      width: 200px;
      height: 200px;
      /* 行内元素水平居中,给父元素设置text-align: center */
      text-align: center;
    }
    
    <!-- html结构 -->
    <div class="box">
      <span>这是span标签</span>
    </div>

image.png

垂直居中实现

.box{
      background-color: red;
      width: 200px;
      height: 200px;
      /* 垂直居中实现 */
      line-height: 200px;
      /* 行内元素水平居中,给父元素设置text-align: center */
      text-align: center;
    }

image.png

最后,给大家附上一张居中方法思维导图

image.png