彻底搞懂水平垂直居中布局(定宽高和不定宽高)

这是面试常问的题目。今天就来彻底搞明白水平垂直居中的方法

一共七种方法,前两种是定宽高才能用的,后面五种不管需要垂直居中的元素有没有宽高都可以垂直居中。flex和table-cell和grid都需要有父元素的宽高,也就是说不能直接在body中水平垂直居中。

<body>
  <div class="container">
    <div class="box">我是小盒子</div>
  </div>
</body>

1.定宽高 绝对定位 + left/right/bottom/top + margin

  .box{
    height: 200px;
    width: 200px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    background-color: red;
  }

2.定宽高 绝对定位和负magin值

 .box{
    height: 200px;
    width: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
  }

3.有宽高和无宽高是一样的 绝对定位 + transform

  .box{
    height: 200px;
    width: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
  }

4.有宽高和无宽高是一样的 flex 父元素必须要有宽高

  .container{
    height: 500px;
    width: 500px;
    background-color: yellow;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .box{
    height: 200px;
    width: 200px;
    background-color: red;
  }

5.有宽高和无宽高是一样的 grid 父元素必须要有宽高

  .container{
    height: 500px;
    width: 500px;
    background-color: yellow;
    display: grid;
  }
  .box{
    /* height: 200px;
    width: 200px; */
    background-color: red;
    margin: auto;
  }

6.有宽高和无宽高差不多 父元素必须要有宽高 table-cell + vertical-align + 直接设置成这个inline-block有宽高无宽高一样。设置margin: auto则时有宽高

 .container{
    height: 500px;
    width: 500px;
    background-color: yellow;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
  }
  .box{
    height: 200px;
    width: 200px;
    background-color: red;
    //margin: auto;
    display: inline-block;
  }

7.定宽高不定宽高可以 flex变异

  .container{
    height: 500px;
    width: 500px;
    background-color: yellow;
    display: flex;
  }
  .box{
    //height: 200px;
    //width: 200px;
    background-color: red;
    margin: auto;
  }
posted @   嘿!那个姑娘  阅读(373)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示