• css实现水平垂直居中的几种方式


    梳理下平时常用css水平垂直居中方式~


    使用flex布局

    HTML

    <div class="box">
      <div class="child"></div>
    </div>
    

    CSS

    .box {
       100vw;
      height: 500px;
      background: skyblue;
    
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .child {
       200px;
      height: 200px;
      background-color: deepskyblue;
    }
    

    利用flex的alignItems:center垂直居中,justifycontent:center水平居中


    利用相对定位和绝对定位的margin:auto

    HTML

    <div class="box">
      <div class="child"></div>
    </div>
    

    CSS

    .box {
       100vw;
      height: 500px;
      background: skyblue;
    
      position: relative;
    }
    
    .child {
       200px;
      height: 200px;
      background-color: deepskyblue;
    
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
    

    相对定位下,使用绝对定位将上下左右都设置为0,再设置margin:auto即可实现居中


    利用相对定位和绝对定位,再加上外边距和平移的配合

    HTML

    <div class="box">
      <div class="child"></div>
    </div>
    

    CSS

    .box {
       100vw;
      height: 500px;
      background: skyblue;
    
      position: relative;
    }
    
    .child {
       200px;
      height: 200px;
      background-color: deepskyblue;
    
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    

    相对定位下,使用绝对定位,利用margin偏移外容器的50%,再利用translate平移回补自身宽高的50%即可


    利用textAlignverticalAlign

    HTML

    <div class="box">
      <div class="child"></div>
    </div>
    

    CSS

    .box {
       100vw;
      height: 500px;
      background: skyblue;
    
      text-align: center;
    }
    
    .box:after {
      content: "";
      display: inline-block;
      height: 100%;
       0;
      vertical-align: middle;
    }
    
    .child {
      display: inline-block;
      vertical-align: middle;
    }
    

    利用textAlign:center实现行内元素的水平居中,再利用verticalAlign:middle实现行内元素的垂直居中,前提是要先加上伪元素并给设置高度为100%,用过elementUI的可以去看看其消息弹窗居中实现方式就是如此


    其他

    上面都是在未知外容器和自身宽高下实现水平垂直居中的,如果已知其宽高,可以有更多种简单的方式实现居中,其原理无非是利用绝对定位的top/left偏移、margin偏移、padding填充,在此就不分析了。还有就是单纯文字的居中利用lineHeighttextAlign即可实现。


    欢迎到前端学习打卡群一起学习~516913974

  • 相关阅读:
    解决在Pycharm中无法显示代码提示的问题
    解决在使用pip list时出现DEPRECATION
    Pycharm 有些库(函数)没有代码提示
    Oracle 11.2.0.4 For Windows 64bit+32bit 数据库
    Windows系统下oracle数据库每天定时备份
    PowerDesigner表创建脚本双引号问题
    Oracle11g 创建数据库中问题处理(必须运行Netca以配置监听程序)
    名人名言
    项目管理
    项目管理心得:一个项目经理的个人体会、经验总结(zz)
  • 原文地址:https://www.cnblogs.com/formercoding/p/12826126.html
Copyright © 2020-2023  润新知