zoukankan      html  css  js  c++  java
  • html元素水平垂直居中

    很多界面需要用到元素水平垂直居中的布局方式。记录一下几种常用的方法

    • 定位法    
    <style>
        body,html{
          background-color: #ccc;
        }
        .box{
           300px;
          height: 300px;
          border: 1px solid red;
          margin: 100px auto;
    
          position: relative;
        }
        .inbox{
           100px;
          height: 100px;
          border: 1px solid blue;
    
          position: absolute;
          left: calc(50% - 50px);
          top: calc(50% - 50px);
        }
      </style>
      <div class="box">
        <div class="inbox"></div>
      </div>
    • 定位结合Css3 (此方法在定位基础上优化了, 子元素宽高未知,也可以居中)
    <style>
        body,html{
          background-color: #ccc;
        }
        .box{
           300px;
          height: 300px;
          border: 1px solid red;
          margin: 100px auto;
    
          position: relative;
        }
        .inbox{
           100px;
          height: 100px;
          border: 1px solid blue;
    
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      </style>
      <div class="box">
        <div class="inbox"></div>
      </div>
    • 空标签法 (不建议使用,但是可以知道有这么个方法存在,适合面试装杯)
    <style>
      .box{ 300px; height: 300px; border: 1px solid red; margin: 100px auto; text
    -align: center; } .inbox{ display: inline-block; } .empty{ display: inline-block; 0; height: 100%; vertical-align: middle; } </style> <div class="box"> <span class="empty"></span> <div class="inbox">水平垂直居中</div> </div>
    • table格子法 (同上)
    <style>
        body,html{
          background-color: #ccc;
        }
        .box{
           300px;
          height: 300px;
          border: 1px solid red;
    
          display: table-cell;
          vertical-align: middle;
        }
        .inbox{
          text-align: center;
        }
      </style>
      <div class="box">
        <div class="inbox">水平垂直居中</div>
      </div>
    • 弹性布局(最实用,最简单)
    <style>
        body,html{
          background-color: #ccc;
        }
        .box{
           300px;
          height: 300px;
          border: 1px solid red;
          margin: 100px auto;
    
          display: flex;
          justify-content: center;
          align-items: center;
        }
      </style>
      <div class="box">
        <div class="inbox">水平垂直居中</div>
      </div>
  • 相关阅读:
    插件模块与模块之间的通信(转)
    C#反射调用其它DLL的委托事件 传值
    单元测试
    c#实现动态加载Dll(转)
    Access sql语句创建表及字段类型(转)
    关于不同数据库表自动转换的功能
    通过DataTable获得表的主键
    C/s程序过时了吗?
    关于C/s结构 本地目录的思考
    关于创建人,创建日期,修改人,修改日期
  • 原文地址:https://www.cnblogs.com/imiliu/p/14367222.html
Copyright © 2011-2022 走看看