• 用CSS 实现 非浮动元素的 水平居中/垂直居中/水平垂直居中


    一.水平居中 

    (1)行内元素解决方案

    只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:

     
    .parent {
        text-align:center;
    }
    

    (2)块状元素解决方案

     
    .item {
        /* 这里可以设置顶端外边距 */
        margin: 10px auto;
    }
    

    (3)多个块状元素解决方案
    将元素的display属性设置为inline-block,并且把父元素的text-align属性设置为center即可:

     
    .parent {
        text-align:center;
    }
    

    (4)多个块状元素解决方案 (使用flexbox布局实现)
    使用flexbox布局,只需要把待处理的块状元素的父元素添加属性display:flex及justify-content:center即可:

     
    .parent {
        display:flex;
        justify-content:center;
    }
    

    二.垂直居中

    (1)单行的行内元素解决方案

    .parent {
        background: #222;
        height: 200px;
    }
    
    /* 以下代码中,将a元素的height和line-height设置的和父元素一样高度即可实现垂直居中 */
    a {
        height: 200px;
        line-height:200px; 
        color: #FFF;
    }
    

    (2)多行的行内元素解决方案
    组合使用display:table-cell和vertical-align:middle属性来定义需要居中的元素的父容器元素生成效果,如下:

    .parent {
        background: #222;
         300px;
        height: 300px;
        /* 以下属性垂直居中 */
        display: table-cell;
        vertical-align:middle;
    }
    

    (3)已知高度的块状元素解决方案

     
    .item{
        top: 50%;
        margin-top: -50px;  /* margin-top值为自身高度的一半 */
        position: absolute;
        padding:0;
    }

    三.水平垂直居中

    (1)已知高度和宽度的元素解决方案1
    这是一种不常见的居中方法,可自适应,比方案2更智能,如下:

    .item{
        position: absolute;
        margin:auto;
        left:0;
        top:0;
        right:0;
        bottom:0;
    }
    

    (2)已知高度和宽度的元素解决方案2

    .item{
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -75px;  /* 设置margin-left / margin-top 为自身高度的一半 */
        margin-left: -75px;
    }
    

    (3)未知高度和宽度元素解决方案

    .item{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */
    }
    

    (4)使用flex布局实现

    .parent{
        display: flex;
        justify-content:center;
        align-items: center;
        /* 注意这里需要设置高度来查看垂直居中效果 */
        background: #AAA;
        height: 300px;
    }
  • 相关阅读:
    【mysql+RBAC】RBAC权限处理(转载:http://www.cnblogs.com/xiaoxi/p/5889486.html 平凡希)
    【小程序】获取微信 自带的 收货地址获取和整理
    【TP3.2】跨库操作和跨域操作
    【JS】一款好用的JS日历选择插件【bootstrap-datetimepicker.js】
    Python 读写文件中w与wt, r与rt的区别
    Python 在序列上跟踪索引和值
    SoapUI 使用变量
    python 跳过可迭代对象的开始部分
    Python 迭代器切片
    Python: 类中为什么要定义__init__()方法
  • 原文地址:https://www.cnblogs.com/zhenguoli/p/8618976.html
Copyright © 2020-2023  润新知