zoukankan      html  css  js  c++  java
  • 实现元素水平居中和垂直居中的几种方法

    情景:父盒子.wrap,子元素.child,实现子元素在父元素中水平和垂直居中

    *{
        padding: 0;
        margin: 0;
    }
    body,html{
        width: 100%;
        height: 100%;
        background-color: #eee;
        overflow: hidden;
    }
    .wrap{
        width: 90%;
        margin: 100px auto;
        background-color: #fff;
        height: 400px;  
    }
    .wrap .child{
        width: 200px;
        height: 200px;
        background-color: red;
    }
    基本样式
    <body>
        <div class="wrap">
            <div class="child"></div>
        </div>
    </body>

    方式一:父元素相对定位,子元素绝对定位,margin:auto

    .wrap{
        position: relative;
    }
    .child{
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

    方式二:父元素相对定位,子元素绝对定位,margin负一半自身宽高

    .wrap{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -100px;
        margin-top: -100px;
    }

    方式三:父元素相对定位,子元素绝对定位,css3位移自身负一半宽高

    .wrap{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }

    方式四:给父盒子使用弹性布局flex

    .wrap{
        display: flex;
        justify-content: center; //主轴
        align-items: center;  //附轴
    }

     方式五:弹性布局,旧的写法

    .wrap{
        display: -webkit-box;
        -webkit-box-pack:center;
        -webkit-box-align:center;
    }
    奔跑的蜗牛
  • 相关阅读:
    位运算学习
    C语言从文件中读取数字
    百度网盘视频加速代码
    算法思想
    递归解决全排列问题
    android studio出现offline情况
    二叉树的遍历(递归与非递归)
    (一)为什么要UML
    Logstash详解之——input模块
    解决maven项目update project会更改jdk版本问题
  • 原文地址:https://www.cnblogs.com/xiaoyue-/p/10650128.html
Copyright © 2011-2022 走看看