zoukankan      html  css  js  c++  java
  • CSS 水平垂直居中

    水平垂直居中

    定位

    1. 百分比, 知道具体宽高

    让盒子距离左上50%,然后向左上移动一半的距离

     #position1 {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -25px;
            margin-left: -50px;
    }
    
    2. 自动,不知道具体宽高

    不需要具体宽高,margin自动填充剩余的空间

    #position2 {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
     }
    
    3. transform, translate, 不需要宽高

    不需要宽高,translate(-50%,-50%)元素在水平方向和垂直方向同时移动,兼容性不好

     #position3 {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
     }
    
    4. JS, 不需要知道具体宽高

    获得父级和盒子元素的宽高,让盒子绝对定位,并使其距离左上位置为剩余空间的一半

    let HTML = document.documentElement,
            winW = HTML.clientWidth,
            winH = HTML.clientHeight,
            box = document.getElementById("box"),
            boxW = box.offsetWidth,
            boxH = box.offsetHeight;
          box.style.position = "absolute";
          box.style.left = (winW - boxW) / 2 + "px";
          box.style.top = (winH - boxH) / 2 + "px";
    

    flex弹性盒模型

    5. flex

    给父节点设置flex盒子,并让他的子元素主轴交叉轴居中,不兼容,移动端常用

     body {
            display: flex;
            justify-content: center;
            align-items: center;
    }
    
  • 相关阅读:
    mysql--创建表,插入数据,修改表名,删除表,简单查询/内连接、左/右连接
    页面访问过程及get/post的理解——
    对docker一些认知
    selenium之css selector定位
    selenium之xpath定位
    Linux常用命令:修改文件权限chmod 754/744
    对redis的一些理解
    用户登录 用例设计
    mysql优化
    mysql复制问题
  • 原文地址:https://www.cnblogs.com/xiaoxu-xmy/p/13695762.html
Copyright © 2011-2022 走看看