zoukankan      html  css  js  c++  java
  • CSS元素垂直居中的几种方法

    在网页响应式布局中,实现水平居中很简单。可是,垂直居中方面,元素的宽度和高度是不可控的,所以很多办法并不适用。

    总结了下平时用到的垂直居中的几种办法:

    demo中HTML代码:

    <div class="center">
            <span></span>
     </div>

    一:使用table-cell;

    CSS代码:

    .table{
      display: table;
      width: 100%;
      height: 100%;
    }
    .center{
      display: table-cell;
      vertical-align:middle;
      text-align: center;
    }
    span{
      display: block;
      width: 100px;
      height: 100px;
      margin: 0 auto;
      background-color: #cecece;
    }

    HTML结构:

    <div class="table">
          <div class="center">
               <span></span>
          </div>
    </div>

    从上面代码可以看出,为了实现垂直居中,添加了额外的元素作为外部容器,且同样要设置外部容器的高度,所以一般情况下不采用这种方式。

    二:使用absolute定位

    CSS代码:

    .center{
            position: relative;
            height: 100%;/*必须定义父级元素的高度*/
            text-align: center;
        }
        span{
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            display: block;
            width: 100px;
            height: 100px;
            margin:auto;/*margin为auto而不是margin:0 auto*/
            background-color: #cecece;
        }

    三:使用translate

    CSS:

    .center{
            position: relative;
            height: 100%;/*必须定义父级元素的高度*/
            text-align: center;
        }
        span{
            position: absolute;
            top: 50%;
            left: 50%;
            right: 0;
            bottom: 0;
            display: block;
            width: 100px;
            height: 100px;
            background-color: #cecece;
            transform:translate(-50%,-50%);
            -webkit-transform:translate(-50%,-50%);
        }

    四:使用flex布局

    CSS:

    .center{
            height: 100%;
            display: flex;
            display: -webkit-flex;
            justify-content:center;
            align-items:center;
        }
        span{
            display: block;
            width: 100px;
            height: 100px;
            margin: 0 auto;
            background-color: #cecece;
        }

    五:使用calc()

    CSS:

    .center{
            position: relative;
            height: 100%;
        }
        span{
            position: absolute;
            top: calc(50% - 50px);
            left: calc(50% - 50px);
            display: block;
            width: 100px;
            height: 100px;
            background-color: #cecece;
        }

    以上五种垂直居中为在项目中使用到的,以后在使用中,可根据页面布局情况选择最合适的方式。

  • 相关阅读:
    Android.mk添加第三方jar包
    关于回调函数
    Ubuntu下GIT服务器的安装与配置
    三星I9100在Ubuntu下用Adb调试
    Android检测网络是否可用和主机是否可达
    keepalived配置文件解析系列之(一)keepalived简介及配置文件介绍
    keepalived配置文件解析系列之(三)配置文件解析过程
    C语言中的位域(bitfield)概念
    popen和变长参数库函数(va_xxx)用法举例及命令执行失败情况探讨
    《深入理解Linux内核》条目式笔记 _3
  • 原文地址:https://www.cnblogs.com/hesuy/p/5629959.html
Copyright © 2011-2022 走看看