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>
  • 相关阅读:
    浏览器兼容模式下,上传文件问题
    计算机编程语言也是一种语言,认识的词汇越多越好
    localhost换成127.0.0.1和本机IP打不开本地项目了的问题
    mvc @html.action() 跨area调用controller 中的action
    windows server 2012 FTP连接报530 User 用户名 cannot log in home directory inaccessible的解决方法
    eCharts 数据转换json
    win10家庭版查看已连接wifi密码
    jequery动态创建form
    jsp 获取配置信息
    docker常用命令
  • 原文地址:https://www.cnblogs.com/imiliu/p/14367222.html
Copyright © 2011-2022 走看看