zoukankan      html  css  js  c++  java
  • 未知宽高的元素水平垂直居中方法总结

    1.父元素设置display:table;子元素设置display:table-cell;

    缺点:IE7不支持,而且子元素会填满父元素,不建议使用

    2.使用css3 transform:translate(-50%; -50%)

    缺点:兼容性不好,IE9+

    3.使用flex布局

    缺点:兼容性不好,IE9+

    4.利用伪类元素

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>未知宽高元素水平垂直居中</title>
    </head>
    <style>
    
        .outer1{
            display: table;
            height:300px;
            width: 300px;
            background-color: #ccc;
            float:left;
            margin:20px;
        }
        .inner1{
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            color: #fff;
            font-size: 16px;
            border:1px solid red;
        }
        .outer2{
            height:300px;
            width: 300px;
            text-align: center;
            background-color: #ccc;
            position:relative;
            float:left;
            margin:20px;
        }
    
        .inner2{
            position: absolute;
            top: 50%;
            left: 50%;
            transform:translate(-50%,-50%);
        }
        .outer3{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 300px;
            height:300px;
            background: #ccc;
            float:left;
            margin:20px;
        }
        .outer4{
            text-align: center;
            width: 300px;
            height:300px;
            background: #ccc;
            float:left;
            margin:20px;
        }
        .outer4:before{
            content:"";
            display: inline-block;
            vertical-align: middle;
            width: 0;
            height: 100%;
        }
        .inner4{
            display: inline-block;
        }
    
    </style>
    <body>
    <div class="outer1">
        <div class="inner1">table-cell 实现</div>
    </div>
    <div class="outer2">
        <div class="inner2">css3</div>
    </div>
    <div class="outer3">
        <div class="inner3">flex布局</div>
    </div>
    <div class="outer4">
        <div class="inner4">伪类元素</div>
    </div>
    </body>
    </html>

    效果:

  • 相关阅读:
    打印对象的 “精心骗局”
    js继承(自备水,这非常干货)
    递归实现深拷贝( 只要学过js递归,看不懂找我包会 )
    PuTTY SSH 使用证书免密码登录
    git 使用
    php socket通信的简单实现
    基于PHP实现短信验证码接口的方法
    PHP实现页面静态化的简单方法分享
    Yii2使用数据库操作汇总(增删查改、事务)
    PHP 获取当前页面的URL信息
  • 原文地址:https://www.cnblogs.com/yaokunlun/p/7442067.html
Copyright © 2011-2022 走看看