zoukankan      html  css  js  c++  java
  • 巧用CSS居中未知高度的块元素

      在网页中让一个未知高度的块元素水平垂直居中是一个老生常谈的问题,但是总是有些特殊场景让你无法得心应手的实现居中,本文介绍几种常用的经典的居中方法,总有一种适合你!

    1. position

    .parent {
        width: 200px;
        height: 200px;
        margin: auto;
        border: 1px solid red;
        position: relative;
    }
    .child {
        position: absolute;
        width: 100px;
        height: 50%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        background-color: red;
    }

    2. flex

    .parent {
        width: 200px;
        height: 200px;
        margin: auto;
        border: 1px solid red;
        display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-box-pack: center;
        -webkit-justify-content: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -webkit-align-items: center;
        -ms-flex-align: center;
        align-items: center;
    }
    .child {
        width: 100px;
        height: 50%;
        background-color: red;
    }

    3. translate

    .parent {
        width: 200px;
        height: 200px;
        margin: auto;
        border: 1px solid red;
        position: relative;
    }
    .child {
        width: 100px;
        height: 50%;
        background-color: red;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }

    4. calc

    .parent {
        width: 200px;
        height: 200px;
        margin: auto;
        border: 1px solid red;
        position: relative;
    }
    .child {
        width: 100px;
        height: 50%;
        background-color: red;
        position: absolute;
        left: -webkit-calc(50% - 25%);
        left: -moz-calc(50% - 25%);
        left: -ms-calc(50% - 25%);
        left: calc(50% - 25%);
        top: -webkit-calc(50% - 25%);
        top: -moz-calc(50% - 25%);
        top: -mz-calc(50% - 25%);
        top: calc(50% - 25%);
    }

      本文介绍的四种方法全部由以下实例验证通过,且加了兼容性前缀,可以直接复制使用,建议使用时可以按顺序考虑,具体可看个人习惯,反正我是这个顺序,因为可以少写很多兼容性前缀,大家可以放心大胆的粘贴使用了,拿贴不谢!

      布局如下:

      效果如下:

  • 相关阅读:
    不怕路长,只怕心老——走在IT行业的路上
    python中 r'', b'', u'', f'' 的含义
    WSGI接口
    HTTP协议简介
    Flask中的Session
    一个 android 开机自动启动功能的例子
    遍历 JObject各属性(CSharp2)
    ASP.NET 伪随机数函数避免重复一例
    浏览器环境下 ES6 的 export, import 的用法举例
    在浏览器环境使用js库(不用require功能)
  • 原文地址:https://www.cnblogs.com/lewiscutey/p/7501974.html
Copyright © 2011-2022 走看看