zoukankan      html  css  js  c++  java
  • div 居中方法汇总

    本文是从简书复制的, markdown语法可能有些出入, 想看"正版"和更多内容请关注 简书: 小贤笔记

    情况一: 父子容器宽高已知

    方法一

    • html
    <div class="father">
        <div class="son"></div>
    </div>
    
    • css
    .father {
        position: relative;
         1000px;
        height: 600px;
        background: lightblue;
    }
    .son {
        position: absolute;
         100px;
        height: 100px;
        background: yellow;
        top: 50%;
        margin-top: -50px; /* 高度的一半 */
        left: 50%;
        margin-left: -50px; /* 宽度的一半 */
    }
    

    方法二

    利用 margin: auto; 自动分配多余空间

    • html
    <div class="father">
        <div class="son"></div>
    </div>
    
    • css
    .father {
        position: relative;
         1000px;
        height: 600px;
        background: lightblue;
    }
    .son {
        position: absolute;
         100px;
        height: 100px;
        background: yellow;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
    }
    

    top、left、right、bottom 的值相等即可,不一定要都是0

    方法三

    用 Flex 布局

    • html
    <div class="father">
        <div class="son"></div>
    </div>
    
    • css
    .father {
         1000px;
        height: 600px;
        background: lightblue;
        display: flex;
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
    }
    .son {
         100px;
        height: 100px;
        background: yellow;
    }
    

    情况二: 父子容器宽高未知

    方法一

    • html
    <div class="father">
        <div class="son"></div>
    </div>
    
    • css
    .father {
        position: relative;
         1000px;
        height: 600px;
        background: lightblue;
    }
    .son {
        position: absolute;
         100px;
        height: 100px;
        background: yellow;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    

    方法二

    用 Flex 布局

    • html
    <div class="father">
        <div class="son"></div>
    </div>
    
    • css
    .father {
         1000px;
        height: 600px;
        background: lightblue;
        display: flex;
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
    }
    .son {
         100px;
        height: 100px;
        background: yellow;
    }
    

    还有其他方法的小伙伴们欢迎补充 谢谢!

  • 相关阅读:
    面试题15 链表中倒数第k个结点
    面试题14 调整数组顺序使奇数位于偶数前面
    面试题13 在O(1)时间删除链表结点
    面试题12 打印1到最大的N位数
    面试题11 数值的整数次方
    面试题10 二进制中1的个数
    面试题9 斐波那契数列
    面试题8 旋转数组的最小数字
    关于神经网络训练的一些建议笔记
    两篇将rf和boosting方法用在搜索排序上的paper
  • 原文地址:https://www.cnblogs.com/shenxianhui/p/9361939.html
Copyright © 2011-2022 走看看